File question

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!

From: Justin To [mailto:[email protected]]

just wondering how I would skip the first line of a file?

then go, play w it using ruby :wink:

File.open(‘file.txt’, ‘r’).each do |line|

# start on the 2nd line

end

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 :wink:

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]]

require ‘fastercsv’

File.open("file.txt’, ‘r’) do |file|

file here is a File object. you can check by printing its class

file.readline

FasterCSV.foreach(“#{file}”) do |row|

 if you print "#{file}", you will know why this will not work

end

end

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!