parse a csv file into a text file

Neil Cerutti neilc at norwich.edu
Thu Feb 6 19:34:55 CET 2014


On 2014-02-06, Tim Chase <python.list at tim.thechases.com> wrote:
> On 2014-02-06 17:40, Mark Lawrence wrote:
>> On 06/02/2014 14:02, Neil Cerutti wrote:
>> >
>> > You must open the file in binary mode, as that is what the csv
>> > module expects in Python 2.7. newline handling can be enscrewed
>> > if you forget.
>> >
>> > file = open('raw.csv', 'b')
>> >
>> 
>> I've never opened a file in binary mode to read with the csv module 
>> using any Python version.  Where does it state that you must do
>> this?
>
> While the docs don't currently say anything about it, all the
> examples at [1] use 'rb' or 'wb' when opening the file.  I've
> long wondered about that.  Especially as I've passed non-file
> objects like lists/iterators to the csv.reader/csv.DictReader
> and had them work just fine (and would be a little perturbed if
> they broke).

They do actually mention it.

From: http://docs.python.org/2/library/csv.html

  csv.reader(csvfile, dialect='excel', **fmtparams)

  Return a reader object which will iterate over lines in the
  given csvfile. csvfile can be any object which supports the
  iterator protocol and returns a string each time its next()
  method is called — file objects and list objects are both
  suitable. If csvfile is a file object, it must be opened with
  the ‘b’ flag on platforms where that makes a difference. 

So it's stipulated only for file objects on systems where it
might make a difference.

-- 
Neil Cerutti




More information about the Python-list mailing list