[英]Process CSV files in location relative to rake task
I have a rake
task and CSV files that I need to process; 我有一个rake
任务和需要处理的CSV文件。 they are located in sub-directory of the lib\\tasks
directory: 它们位于lib\\tasks
目录的子目录中:
\foo
one.csv
two.csv
...
foo.rake
The task: 任务:
task foo: :environment do
# for each file in directory
Dir.foreach("./*.csv") do |file| # not valid
# process CSV file's content
CSV.foreach(file, {:headers => true, :col_sep => ";"}) do |row|
...
end
end # Dir
end # task
How do I references files that are relative to the rake task? 如何引用与rake任务相关的文件?
I got to thinking about this more and I think combining File.join
and Dir.glob
will allow you to process all your csv files: 我需要考虑更多,我认为结合File.join
和Dir.glob
将允许您处理所有的csv文件:
require "csv"
foo_dir = File.join(Rails.root, "lib", "tasks", "foo")
task foo: :environment do
# for each file in directory
Dir.glob(foo_dir + "/*.csv") do |csv_file|
# process CSV file's content
CSV.foreach(csv_file, {:headers => true, :col_sep => ";"}) do |row|
#...
end
end # Dir
end # task
EDIT: As @craig pointed out in the comment below, this can be accomplished more succinctly by using File.dirname
and __FILE__
: 编辑:正如@craig在下面的注释中指出的那样,可以通过使用File.dirname
和__FILE__
更加简洁地完成此操作:
require "csv"
task foo: :environment do
# for each file in directory
Dir.glob(File.dirname(__FILE__) + "/*.csv").each do |file|
# process CSV file's content
CSV.foreach(csv_file, {:headers => true, :col_sep => ";"}) do |row|
#...
end
end # Dir
end # task
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.