【发布时间】:2019-08-10 13:18:36
【问题描述】:
我想从 CSV 文件中删除前两行并添加我自己的标题。我已将其包装在 rake 任务中。
task :fix_csv do
# copy to temp file
cp ENV['source'], TMP_FILE
# drop header rows
table = CSV.table(TMP_FILE)
File.open(TMP_FILE, 'w') do |f|
f.write(table.drop(2).to_csv)
end
# add new header
CSV.open(TMP_FILE, 'w', force_quotes: true) do |csv|
csv << HEADERS if csv.count.eql? 0
end
puts 'Done!'
end
但是,这会失败并出现错误:
rake aborted!
IOError: not opened for reading
../rakefile.rb:54:in `count'
第 54 行是:
csv << HEADERS if csv.count.eql? 0
为什么不能读取文件?删除前两行后,是否需要显式关闭文件?
【问题讨论】: