Hi, just wondering how I would skip the first line of a file?
File.open(‘file.txt’, ‘r’).each do |line|
start on the 2nd line
end
Thanks!
Hi, just wondering how I would skip the first line of a file?
File.open(‘file.txt’, ‘r’).each do |line|
end
Thanks!
From: Justin To [mailto:[email protected]]
then go, play w it using ruby
as always, there are many ways (depennding on your taste),
eg given a file,
File.open(‘file.txt’, ‘r’).each do |line|
p line
end
“1234\n”
“456\n”
“4321\n”
“654\n”
“546\n”
“3456\n”
“5436\n”
“9879\n”
“1111\n”
#=> #<File:file.txt>
you can skip the line by referring to it’s index,
File.open(‘file.txt’, ‘r’).each_with_index do |line,index|
next if index == 0
p line
end
“456\n”
“4321\n”
“654\n”
“546\n”
“3456\n”
“5436\n”
“9879\n”
“1111\n”
or just skip it by reading and discarding it
File.open(‘file.txt’, ‘r’) do |file|
file.readline
file.each do |line|
p line
end
end
“456\n”
“4321\n”
“654\n”
“546\n”
“3456\n”
“5436\n”
“9879\n”
“1111\n”
#=> #<File:file.txt (closed)>
note i prefer the latter since its clearer (to me), and it does not
annoy the loop
kind regards -botp
Thanks, helps a lot. How about if I am using FasterCSV?
require ‘fastercsv’
File.open(“file.txt’, ‘r’) do |file|
file.readline
FasterCSV.foreach(”#{file}") do |row|
end
end
Invalid argument #<file…>
Mmm… not sure how I would do it then! =)
Thanks
From: [email protected] [mailto:[email protected]]
file here is a File object. you can check by printing its class
if you print "#{file}", you will know why this will not work
again, there are many ways in ruby, eg, given a file,
File.open(“csv.txt”).each do |line|
p line
end
“"skip this"\n”
“"123","abc"\n”
“"456","def"\n”
“"678","zyx"\n”
#=> #<File:csv.txt>
we can skip the first line, and then parse the rest of the lines using
fastercsv like,
File.open “csv.txt” do |file|
file.readline
file.each do |line|
p FasterCSV.parse_line(line)
end
end
[“123”, “abc”]
[“456”, “def”]
[“678”, “zyx”]
#=> #<File:csv.txt (closed)>
or
you can just plainly open the file using fastercsv, and notifying fcsv
that the first line is a header, like,
FasterCSV.foreach(“csv.txt”,{:headers=>:first_row}) do |line|
puts line
end
123,abc
456,def
678,zyx
#=> nil
kind regards -botp
Terrific, thanks so much!
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs