[英]Generate CSV from Ruby results
I currently have this script that generates usernames from a given CSV. 我目前有一个脚本,可以从给定的CSV生成用户名。 Rather than printing these results to the console, how can I write a new CSV with these results? 与其将这些结果打印到控制台,不如将这些结果写入新的CSV文件?
This is the script I currently have, runs with no errors. 这是我目前拥有的脚本,运行时没有错误。 I am assuming if I write a new CSV in the do |row| 我假设是否在do | row |中编写了新的CSV文件。 block it is going to create x amount of new files which I do not want. 阻止它会创建x个我不想要的新文件。
require 'csv'
CSV.foreach('data.csv', :headers => true) do |row|
id = row['id']
fn = row['first_name']
ln = row['last_name']
p fn[0] + ln + id[3,8]
end
Just manage the CSV file to write around the reading: 只需管理CSV文件即可在阅读范围内书写内容:
CSV.open("path/to/file.csv", "wb") do |csv|
CSV.foreach('data.csv', :headers => true) do |row|
id = row['id']
fn = row['first_name']
ln = row['last_name']
csv << [fn[0], ln, id[3,8]]
# or, to output it as a single column:
# csv << ["#{fn[0]}#{ln}#{id[3,8]}"]
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.