2012-03-08 96 views
12

我正在使用ruby的文件打開並讀取耙子 任務中的文本文件。有沒有一個設置,我可以指定我想跳過文件的第一行 ? 這裏是我到目前爲止的代碼:在1.9.3中讀取文件時跳過第一行

desc "Import users." 
    task :import_users => :environment do 
    File.open("users.txt", "r", '\r').each do |line| 
     id, name, age, email = line.strip.split(',') 
     u = User.new(:id => id, :name => name, :age => age, :email => email) 
     u.save 
    end 
    end 

我試圖line.lineno也做File.open("users.txt", "r", '\r').each do |line, index|next if index == 0,但還沒有任何運氣。

回答

21

更改eacheach_with_index do |line, index|next if index == 0將工作。

9
File.open("users.txt", "r", '\r') do |file| 
    lines = file.lines # an enumerator 
    lines.next #skips first line 
    lines.each do |line| 
    puts line # do work 
    end 
end 

利用一個枚舉器,它'記住'它在哪裏。

4

你可能真的要使用CSV:

CSV.foreach("users.txt", :headers, :header_converters => :symbol, :col_sep => ',') do |row| 
    User.new(row).save 
end 
4
File.readlines('users.txt')[1..-1].join() 

作品也很好。

14

功能drop(n)將從開頭刪除n行:

File.readlines('users.txt').drop(1).each do |line| 
    puts line 
end 

它將讀取整個文件到一個數組並取出第一n線。如果你正在閱讀整個文件,這可能是最優雅的解決方案。

f = File.open('users.txt', 'r') 
first_line = f.gets 
body = f.readlines 

更可能的是,你想要的是處理:如果你想將文件保存爲IO整個時間(沒有數組轉換),並且計劃在第一行中使用數據

+0

您的意思是File.readlines(「users.txt」)。drop(1).each do | line | ,你的例子給出了一個錯誤 – peter 2014-10-29 16:38:44

+0

是的,當然。它應該是'File.readlines'。謝謝@peter! – Tombart 2014-10-29 19:54:57

+0

這應該是公認的答案! – jpatokal 2015-05-05 12:59:21

1

CSV或FasterCSV等人指出。我最喜歡的方式來處理與標題行的文件是要做到:

FasterCSV.table('users.txt') 
1

由於幾個答案(?不再)工作的Ruby 1.9.3,這裏的三個最佳方法工作示例

# this line must be dropped 
puts "using drop" 
File.readlines(__FILE__).drop(1).each do |line| 
    puts line 
end 
puts "" 

puts "using a range" 
File.readlines(__FILE__)[1..-1].each do |line| 
    puts line 
end 
puts "" 

puts "using enumerator" 
File.readlines(__FILE__).each do |file, w| 
    lines = file.lines # an enumerator 
    lines.next #skips first line 
    lines.each do |line| 
     puts line 
    end 
end 
相關問題