How to change headers in a CSV file using FasterCSV and then save new headers?

I'm having trouble understanding: header_converters and: converters in FasterCSV. Basically, all I want to do is change the column headers to the corresponding column names.

sort of:

FasterCSV.foreach(csv_file, {:headers => true, :return_headers => false, :header_converters => :symbol, :converters => :all} ) do |row|
    puts row[:some_column_header] # Would be "Some Column Header" in the csv file.

execpt I'm not sure: the character and: everything in the converter parameters.

+3
source share
3 answers

A converter :allmeans that it is trying to use all the built-in converters, in particular:

:integer:   Converts any field Integer() accepts.
:float:     Converts any field Float() accepts.
:date:      Converts any field Date::parse() accepts.
:date_time: Converts any field DateTime::parse() accepts.

, , ( ), , . , row[i], String '9', .

. , - :

FastCSV.foreach(some_file, :header_converters => :downcase) do |row|

"Some Header" row['some header'].

:symbol , row[:some_header]. , , a-z, 0-9 _. , , .

row['some header'], :header_converter.


EDIT:

headers_convert , , . , . :return_headers, . , - :

require 'fastercsv'

input = File.open 'original.csv', 'r'
output = File.open 'modified.csv', 'w'
FasterCSV.filter input, output, :headers => true, :write_headers => true, :return_headers => true do |row|
  change_headers(row) if row.header_row?
end
input.close
output.close

, :

FileUtils.mv 'modified.csv', 'original.csv', :force => true
+9

. FasterCSV . , ~ 7 , , - , , .

CSV FasterCSV :header_converters , . (header_converters: :symbol) (header_converters: lambda {...}). CSV- , , . CSV, .

:

options = {
  headers: true,
  header_converters: lambda { |h| HEADER_MAP.keys.include?(h.to_sym) ? HEADER_MAP[h.to_sym] : h }
}

table = CSV.read(FILE_TO_PROCESS, options)

File.open(PROCESSED_FILE, "w") do |file|
  file.write(table.to_csv)
end
+1

CSV , CSV .

, , :

lookup_headers = { "old": "new", "cat": "dog" } # The desired header swaps

CSV($>, headers: true, write_headers: true) do |csv_out|
  CSV.foreach( ARGV[0],
               headers: true, 
               # the following lambda replaces the header if it is found, leaving it if not...
               header_converters: lambda{ |h| lookup_headers[h] || h}, 
               return_headers: true) do |master_row|

    if master_row.header_row?
      # The headers are now correctly replaced by calling the updated headers
      csv_out << master_row.headers
    else
      csv_out << master_row
    end
  end
end

, !

0
source

Source: https://habr.com/ru/post/1709612/


All Articles