| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Name | Name | Last commit date | ||
|---|---|---|---|---|
Basic files for SL URUG meeting on 9/23/2014 and a quick discussion on csv files in general and fastercsv and it's usage in ruby
in ruby version 1.9.2 the CSV standard library was replaced with a library called fastercsv. this library is authored by James Edward Gray II.
traditionally, csv stood for 'comma seperated value' file but it has come to be more accurate to call them 'character seperated value' files because many applications want to use alternate seperators (often the pipe '|' or other characters).
Most csv files utilize the first row to label the columns included below but that isn't necessarily required. It's a nice convenience though and, with fastercsv, allows you to reference the columns as they are read by name rather than by position. This also allows files to be consumed if the columns are not in a set order from delivery to delivery without any problems.
Ruby has built in string processing methods that are great. If the csv file is not mal-formed in any way and doesn't have any quoted fields, then parsing an entry is simply
data.split(',')
the problem arrises when we want to quote fields to allow for embedded commas in a comma separated file, or other embedded delimiter characters. That's where it gets a little dicey and the library makes life dramatically easier.
The basic pattern I've used for reading CSV files is below
require 'csv'
CSV.foreach('myfilename', {:headers => :first_row}) do |row|
# skip blank and commented rows
next if row.nil? || row.empty? || row[0][0] == '#'
# convert to hash to be able to read by column name
hash = row.to_hash
# process row or hash contents from file
... do stuff here ...
end
Basic things to discuss and watch out for:
The challenge this month is to build a parser to read csv files. The parameters are as follows:
we will not use a non UTF8 file encoding or non-ascii chars so no worries there.
There are some sample files in the import_files directory.
the challenge will read some files that represent sales transactions for some kinds of products. the sample files are selling computer/office supplies. there are 2 files: a products file and a transactions file. read the files using your csv parser and report the following in your output:
| Back | FazBrowse Home | New Git URL |