Count the length (number of lines) of a CSV file?

后端 未结 7 1182
野性不改
野性不改 2020-12-31 02:46

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

    <% form_for(:upcsv, :html => {:multipa         


        
7条回答
  •  时光说笑
    2020-12-31 03:06

    Just to demonstrate what IO#readlines does:

    if you had a file like this: "asdflkjasdlkfjsdakf\n asdfjljdaslkdfjlsadjfasdflkj\n asldfjksdjfa\n"

    in rails you'd do, say:

    file = File.open(File.join(Rails.root, 'lib', 'file.json'))
    lines_ary = IO.readlines(file)
    lines_ary.count #=> 3
    

    IO#readlines converts a file into an array of strings using the \n (newlines) as separators, much like commas so often do, so it's basically like

    str.split(/\n/)
    

    In fact, if you did

     x = file.read
    

    this

     x.split(/\n/)
    

    would do the same thing as file.readlines

    ** IO#readlines can be really handy when dealing with files which have a repeating line structure ("child_id", "parent_ary", "child_id", "parent_ary",...) etc

提交回复
热议问题