Print

Print


I concur with Dan that Python's stdlib CSV module (
http://docs.python.org/2/library/csv.html) is a little bit janky, but it's
there to cover the simple use cases straightforwardly and has a fair amount
of flexibility to adapt to different styles of input and output.  But in
the simplest case ("true" CSV) it's usually as simple as:

from csv import reader
rows = list(reader(open("thing.csv"))

And if it's tab-delimited instead, either use dialect='excel-tab' or
delimiter='\t' and you are probably OK if they used the sane default of
wrapping fields that contain tabs with double quotes (this applies to the
default comma separator too, btw).  If you need something different or more
aggressive, you can get to it by messing with the Dialect (e.g. what if the
'escaping' quotes in the source are single quotes?  quotechar!).

from csv import reader
from cStringIO import StringIO
# just so I can treat a string like a file

x = "\t".join(['Field1', '"Field2\tFAKEOUT"','Field3,and friend', 'field4'])
# x is now """Field1\t"Field2\t FAKEOUT"\tField3,and friend\tfield4"""

rows = list(reader(StringIO(x),delimiter='\t')
# rows is now ["Field1","Field2\tFAKEOUT","Field3, and friend","field4"]

All the dialect stuff is there to let you build up your own library to deal
with "WhateverSV" that comes in from the wild, but as long as your data
sources are reasonably well-behaved (like Excel?) you probably don't need
to delve into it.  So, complex, yeah, a bit, but flexible. I'm not sure I
can come up with something obviously better on my own =)

cheers,

AC




On Mon, Nov 25, 2013 at 2:28 PM, Dan Scott <[log in to unmask]> wrote:

> Hi Bohyun:
>
> I found the CSV module in Python to be surprisingly confusing when I
> first encountered it, given Python's elegance in many other cases. The
> Dialect thing drove me nuts at first!
>
> Lots of other people have answered in bits and pieces in this thread,
> including non-Python approaches, but here's what works for me (with
> the single example row that you've provided):
>
> import csv
> with open('noid_refworks.txt','rU') as csvinput:
>     with open('withid.txt', 'w') as csvoutput:
>         csvinput.seek(0)
>         reader = csv.reader(csvinput, 'excel-tab')
>         writer = csv.writer(csvoutput, 'excel-tab', quoting=csv.QUOTE_NONE)
>         for row in reader:
>             row.insert(0, '')
>             writer.writerow(row)
>
> The two changes that I've made were:
>
> 1. Remove the dialect sniffer and provide one explicitly ('excel-tab',
> which uses a tab-delimited format); with the single line example, my
> sniffer kept thinking the dialect was comma-delimited, which was
> _very_ confusing to me :)
> 2. row.insert(0, '') before writing the row to prepend an empty
> element at the start of the list, instead of building a new list with
> an explicit tab (which would end up having to be escaped, which might
> be why it shows up as an L in your output)
>
> This snippet works in both Python 2.7.5 and Python 3.3.3 for me.
>
> Hope this helps,
> Dan
>
>
> On Mon, Nov 25, 2013 at 12:10 PM, Bohyun Kim <[log in to unmask]> wrote:
> > Hi all,
> >
> > I am new to Python and was wondering if I can get some help with my
> short script. What I would like the script to do is:
> > (1) Read the tab delimited file generated by Refworks
> > (2) Output exactly the same file but the blank column added in front.
> > (This is for prepping the exported tab delimited file from refworks so
> that it can be imported into MySQL; so any suggestions in the line of
> timtoady would be also appreciated.)
> >
> > This is what I have so far. It works, but then in the output file, I end
> up getting some weird character in each line in the second column (first
> column in the original input file). I also don't really get what
> escapechar=' ' does or what I am supposed to put in there.
> >
> > import csv
> > with open('noid_refworks.txt','rU') as csvinput:
> >     with open('withid.txt', 'w') as csvoutput:
> >         dialect = csv.Sniffer().sniff(csvinput.read(1024))
> >         csvinput.seek(0)
> >         reader = csv.reader(csvinput, dialect)
> >         writer = csv.writer(csvoutput, dialect, escapechar='\'',
> quoting=csv.QUOTE_NONE)
> >         for row in reader:
> >             writer.writerow(['\t']+row)
> >
> > A row in the original file is like this (Tab delimited and no
> quotations, some fields have commas and quotation marks inside.):
> >
> > Reference Type    Authors, Primary    Title Primary    Periodical Full
>  Periodical Abbrev    Pub Year    Pub Date Free From    Volume    Issue
>  Start Page    Other Pages    Keywords    Abstract    Notes    Personal
> Notes    Authors, Secondary    Title Secondary    Edition    Publisher
>  Place Of Publication    Authors, Tertiary    Authors, Quaternary
>  Authors, Quinary    Title, Tertiary    ISSN/ISBN    Availability
>  Author/Address    Accession Number    Language    Classification    Sub
> file/Database    Original Foreign Title    Links    DOI    Call Number
>  Database    Data Source    Identifying Phrase    Retrieved Date
>  Shortened Title    User 1    User 2    User 3    User 4    User 5    User
> 6    User 7    User 8    User 9    User 10    User 11    User 12    User 13
>    User 14    User 15
> >
> > A row in the output file is like this:
> > (The tab is successfully inserted. But I don't get why I have L inserted
> after no matter what I put in escapechar)
> >
> >     LReference Type    Authors, Primary    Title Primary    Periodical
> Full    Periodical Abbrev    Pub Year    Pub Date Free From    Volume
>  Issue    Start Page    Other Pages    Keywords    Abstract    Notes
>  Personal Notes    Authors, Secondary    Title Secondary    Edition
>  Publisher    Place Of Publication    Authors, Tertiary    Authors,
> Quaternary    Authors, Quinary    Title, Tertiary    ISSN/ISBN
>  Availability    Author/Address    Accession Number    Language
>  Classification    Sub file/Database    Original Foreign Title    Links
>  DOI    Call Number    Database    Data Source    Identifying Phrase
>  Retrieved Date    Shortened Title    User 1    User 2    User 3    User 4
>    User 5    User 6    User 7    User 8    User 9    User 10    User 11
>  User 12    User 13    User 14    User 15
> >
> >
> > Any help or pointers would be greatly appreciated!
> > ~Bohyun
>