Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing whitespaces in a CSV file

I have a string with extra whitespace:

First,Last,Email  ,Mobile Phone ,Company,Title  ,Street,City,State,Zip,Country, Birthday,Gender ,Contact Type

I want to parse this line and remove the whitespaces.

My code looks like:

namespace :db do
task :populate_contacts_csv => :environment do

require 'csv'

csv_text = File.read('file_upload_example.csv')
  csv = CSV.parse(csv_text, :headers => true)
    csv.each do |row|
      puts "First Name: #{row['First']} \nLast Name: #{row['Last']} \nEmail: #{row['Email']}"
    end
  end
end
like image 834
xdsemx Avatar asked Jan 21 '13 15:01

xdsemx


People also ask

Do CSV files use whitespace?

CSV files without whitespace is for machine (software) reading, OR where you can have a common separator that is not used elsewhere - if you want to avoid the path of escaping the separators. Fixed-width-files are better for humans, or where the separator chosen will at times be part of the text.

How do I remove spaces from a CSV file in Python?

To skip initial space from a Pandas DataFrame, use the skipinitialspace parameter of the read_csv() method. Set the parameter to True to remove extra space.


2 Answers

@prices = CSV.parse(IO.read('prices.csv'), :headers=>true, 
   :header_converters=> lambda {|f| f.strip},
   :converters=> lambda {|f| f ? f.strip : nil})

The nil test is added to the row but not header converters assuming that the headers are never nil, while the data might be, and nil doesn't have a strip method. I'm really surprised that, AFAIK, :strip is not a pre-defined converter!

like image 58
Mike Blyth Avatar answered Sep 29 '22 06:09

Mike Blyth


You can strip your hash first:

csv.each do |unstriped_row|
  row = {}
  unstriped_row.each{|k, v| row[k.strip] = v.strip}
  puts "First Name: #{row['First']} \nLast Name: #{row['Last']} \nEmail: #{row['Email']}"
end

Edited to strip hash keys too

like image 34
Anthony Alberto Avatar answered Sep 29 '22 08:09

Anthony Alberto