[Tutor] csv manipulation

Kent Johnson kent37 at tds.net
Wed Oct 29 18:31:00 CET 2008


On Wed, Oct 29, 2008 at 11:28 AM, bob gailer <bgailer at gmail.com> wrote:
> qsqgeekyogdty at tiscali.co.uk wrote:
>>
>> hello,
>> i have the follwoing csv file:
>>
>> "Berat","Berat","Kuçovë","Skrapar"

> There is a csv module, but for something this simple the following will
> suffice:

as long as none of the data fields include a comma...given that the
equivalent program using csv is barely longer than your example, and
more robust, it seems worth using to me. For example (untested):

import csv

inputFile= open(path-to-the-input-file, 'rb')
reader = csv.reader(inputFile)
outputFile = open(path-to-the-output-file, 'wb')
writer = csv.writer(outputFile)

for line in reader:
 region = line [0]
 for district in line[1:]:
  writer.write((region, district))
inputFile.close()
outputFile.close()

Kent


More information about the Tutor mailing list