首页 > 解决方案 > 如何让这个 ruby​​ 脚本输出与另一个 CSV 文件相同的行和列并向其中添加另一列?

问题描述

该脚本的目标是为 useradd linux 命令生成用户名。我还希望使用新生成的名称和密码将名称相同的名称以相同的顺序放入一个新的 CSV 文件中。

到目前为止,我已经有了通过读取 CSV 文件来生成新名称的脚本。

CSV 文件的前两行如下所示。

first_name, last_name
Briana, Considine

这是有效的脚本部分:

filename = 'employeedata.csv'

CSV.foreach(filename, headers: true) do |row|
   first_name_char = row['first_name'].strip.split('')
   useradd_name = "#{row['last_name']}#{first_name_char.first}#{first_name_char.last}"
   password = ""; 8.times{value << ((rand(2)==1?65:97) + rand(25)).chr}
   system("useradd '#{useradd_name}'")
   puts useradd_name
   puts password

这是脚本中出错的部分。

   CSV.open("GeneratedUsers.csv", "w") do |outfile|
        outfile << ["First Name", "Last Name:", "Username:"] #to make the new headers
        outfile << "#{row['first_name']}" #import firstname from employeedata.csv
   end
end

这是我得到的错误:

Traceback (most recent call last):
        17: from Nick_Hyder_Project3.rb:19:in `<main>'
        16: from C:/Ruby26-x64/lib/ruby/2.6.0/csv.rb:509:in `foreach'
        15: from C:/Ruby26-x64/lib/ruby/2.6.0/csv.rb:657:in `open'
        14: from C:/Ruby26-x64/lib/ruby/2.6.0/csv.rb:510:in `block in foreach'
        13: from C:/Ruby26-x64/lib/ruby/2.6.0/csv.rb:1236:in `each'
        12: from C:/Ruby26-x64/lib/ruby/2.6.0/csv.rb:1236:in `each'
        11: from C:/Ruby26-x64/lib/ruby/2.6.0/csv/parser.rb:303:in `parse'
        10: from C:/Ruby26-x64/lib/ruby/2.6.0/csv/parser.rb:779:in `parse_quotable_loose'
         9: from C:/Ruby26-x64/lib/ruby/2.6.0/csv/parser.rb:28:in `each_line'
         8: from C:/Ruby26-x64/lib/ruby/2.6.0/csv/parser.rb:28:in `each_line'
         7: from C:/Ruby26-x64/lib/ruby/2.6.0/csv/parser.rb:31:in `block in each_line'
         6: from C:/Ruby26-x64/lib/ruby/2.6.0/csv/parser.rb:827:in `block in parse_quotable_loose'
         5: from C:/Ruby26-x64/lib/ruby/2.6.0/csv/parser.rb:1078:in `emit_row'
         4: from Nick_Hyder_Project3.rb:25:in `block in <main>'
         3: from C:/Ruby26-x64/lib/ruby/2.6.0/csv.rb:657:in `open'
         2: from Nick_Hyder_Project3.rb:27:in `block (2 levels) in <main>'
         1: from C:/Ruby26-x64/lib/ruby/2.6.0/csv.rb:1186:in `<<'
C:/Ruby26-x64/lib/ruby/2.6.0/csv/writer.rb:37:in `<<': undefined method `collect' for "Briana":String (NoMethodError)

在将新用户名和密码添加到新列之前,有没有办法复制所有旧文件?还是我需要逐行编写新的 CSV?

标签: rubycsvparsing

解决方案


CSV 数据的行需要是数组。所以这一行:

  outfile << "#{row['first_name']}"

应该:

  outfile << [row['first_name']]

但是,由于您可能想要添加几行,您应该重新排列循环代码以首先打开输出文件,然后处理输入行:

CSV.open("GeneratedUsers.csv", "w") do |outfile|
  # Headers for outfile
  outfile << ["First Name", "Last Name:", "Username:"] 

  # Process users
  CSV.foreach(filename, headers: true) do |row|
    ...code to add user etc...
    ...
    # Append new user to outfile
    outfile << [row['first_name'], row['last_name'], useradd_name]
  end
end

推荐阅读