【问题标题】:How to fix headers in csv file with Ruby then copy to postgresql database?如何使用 Ruby 修复 csv 文件中的标题然后复制到 postgresql 数据库?
【发布时间】:2019-05-22 05:39:00
【问题描述】:

我想使用 Ruby 将 CSV 文件导入 PostgreSQL 表。我希望自动完成(通过任务),因为具有相同结构的新文件将每月导入。它首先复制到一个临时表,在本例中为“test”,然后插入到另一个表中。

这是我想做的:

  • CSV 文件的某些标题包含空格,我希望将它们替换为下划线,这样我以后就不必处理这些了。例如,“col 1”需要变为“col_1”。
  • CSV 文件中的某些列是无用的,我不希望将它们复制到数据库中。例如,在“col_1”、“col_2”和“col_3”中,我只想复制“col_1”和“col_3”。

这是我正在使用的 CSV 内容:

col 1,col 2,col 3
r1c1,r1c2,r1c3
r2c1,r2c2,r2c3

通过在stackoverflow和其他地方搜索,这是我得到的以下代码。

task :insert_charge [:file] => :environment do |task,args|
  require 'csv'
  testfile = CSV.read(args[:file],
    :headers => true,
    :converters => :all,
    :header_converters => lambda { |h| h.gsub(' ', '_') }
  )

   ActiveRecord::Base.connection.execute("
    drop table if exists test;
    create table test (
      id serial primary key,
      col_1 varchar(4),
      col_3 varchar(4)
    );
  ")

  conn = PG::Connection.open(
    :user => Rails.configuration.database_configuration["development"]["username"],
    :dbname => Rails.configuration.database_configuration["development"]["database"],
    :password => Rails.configuration.database_configuration["development"]["password"]
  )

  conn.copy_data "copy test (col_1, col_3)
    from stdin csv header delimiter ',' null as '' encoding 'utf-8'" do
    conn.put_copy_data testfile
  end
end

我成功地能够使用下划线更改标题中的空格。但是,这会将 CSV 更改为表格模式,然后无法将其复制到数据库中。如何修改标头,然后将 CSV 复制到数据库中?

这是我在执行rake insert_charge [d:\\test.csv] 时遇到的错误: TypeError:CSV::Table 参数类型错误(预期字符串)

请考虑到我是一个真正的 Ruby 初学者。我见过与我类似的问题,但没有适合我的问题的答案。

感谢您的帮助!

【问题讨论】:

    标签: ruby postgresql csv


    【解决方案1】:

    也许你可以考虑修复头文件重写文件,改变第一行:

    lines = File.readlines('test.csv')
    new_header = lines[0].chomp.split(',').map{ |w| w.gsub(' ', '_')}.join(',')
    lines[0] = new_header << $/
    File.open('test.csv', 'w') { |f| f.write(lines.join) }
    

    如果您不想覆盖文件,只需更改输出文件的名称即可。

    (此处被盗:https://stackoverflow.com/a/35958805

    那么您可能不需要使用csv 库读取文件,将字符串传递给进程,请尝试:

    testfile = File.read('test.csv')
    p testfile.class #=> String
    

    【讨论】:

      猜你喜欢
      • 2013-07-13
      • 1970-01-01
      • 1970-01-01
      • 2019-09-26
      • 1970-01-01
      • 1970-01-01
      • 2022-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多