计算CSV文件的长度(行数)? [英] Count the length (number of lines) of a CSV file?

查看:1551
本文介绍了计算CSV文件的长度(行数)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单(Rails),它允许我使用 file_field 加载.csv文件。
在视图中:

I have a form (Rails) which allows me to load a .csv file using the file_field. In the view:

    <% form_for(:upcsv, :html => {:multipart => true}) do |f| %>
    <table>
        <tr>
            <td><%= f.label("File:") %></td>
            <td><%= f.file_field(:filename) %></td>
        </tr>
    </table>
        <%= f.submit("Submit") %>
    <% end %>

单击提交将我重定向到另一个页面(create.html.erb)。文件加载得很好,我能够在第二页中读取内容很好。我试图在第二页中显示.csv文件中的行数。

Clicking Submit redirects me to another page (create.html.erb). The file was loaded fine, and I was able to read the contents just fine in this second page. I am trying to show the number of lines in the .csv file in this second page.

我的控制器(半伪代码):

My controller (semi-pseudocode):

class UpcsvController < ApplicationController
    def index
    end

    def create
        file = params[:upcsv][:filename]
        ...
        #params[:upcsv][:file_length] = file.length # Show number of lines in the file
        #params[:upcsv][:file_length] = file.size
        ...
    end
end

两个 file.length file.size 返回'91',当我的文件只包含7行。从我读的Rails文档,一旦点击提交按钮,Rails创建一个上传的文件的临时文件, params [:upcsv] [:filename] 包含临时/上传文件的内容,而不是文件的路径。我不知道如何提取我的原始文件中的行数。获取文件中行数的正确方法是什么?

Both file.length and file.size returns '91' when my file only contains 7 lines. From the Rails documentation that I read, once the Submit button is clicked, Rails creates a temp file of the uploaded file, and the params[:upcsv][:filename] contains the contents of the temp/uploaded file and not the path to the file. And I don't know how to extract the number of lines in my original file. What is the correct way to get the number of lines in the file?

我的create.html.erb:

My create.html.erb:

<table>
    <tr>
        <td>File length:</td>
        <td><%= params[:upcsv][:file_length] %></td>
    </tr>
</table>

我真的是Rails的新用户(刚刚上周开始),所以请承担我的愚蠢问题。

I'm really new at Rails (just started last week), so please bear with my stupid questions.

谢谢!

更新:显然,数字'91'在我的文件中的单个字符数(包括回车)。我的文件中的每一行都有12位数字+ 1新行= 13. 91/13 = 7。

Update: apparently that number '91' is the number of individual characters (including carriage return) in my file. Each line in my file has 12 digits + 1 newline = 13. 91/13 = 7.

推荐答案

行数

file.readlines.size

这篇关于计算CSV文件的长度(行数)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆