mrpopo
mrpopo

Reputation: 1563

Python: How can I create a data file from a converted csv file?

I am trying to convert a csv file into another file (file type doesn't matter as the program using the converted data just opens it like a text file).

So far I have managed to convert and print the original csv data into the the data structure I want but I now need to save that as another file.

import csv
file = open('newData', 'w')

with open('initialData.csv', 'rb') as f:
reader = csv.reader(f, delimiter=',', quotechar='|')
for row in reader:
    print row[13] + ' 1:' + row[0] + ' 2:' + row[1]
    file.write(f)

file.close()

Whenever I run this I get the error:

TypeError: expected a character buffer object

I know there is nothing wrong with converting the csv file as that prints fine when I comment out the file.write(f).

Many thanks in advance!

Upvotes: 1

Views: 231

Answers (2)

Blair
Blair

Reputation: 15788

Why are you trying to write the original file (the f object) to the new file? Don't you want to write the re-formatted data?

import csv

with open('initialData.csv', 'rb') as f_in, open('newData', 'w') as f_out:
    reader = csv.reader(f_in, delimiter=',', quotechar='|')
    for row in reader:
        print row[13] + ' 1:' + row[0] + ' 2:' + row[1]
        f_out.write(row[13] + ' 1:' + row[0] + ' 2:' + row[1])

Edit: as suggested by Jon Clements, use context manager for output as well + indentation fix.

Upvotes: 8

millimoose
millimoose

Reputation: 39950

You're trying to print out the file handle for the whole csv file. I'm guessing you want the text you're printing to be written out into a file, in that case just do:

with open('initialData.csv', 'rb') as infile, open('newData.txt') as outfile:
    reader = csv.reader(infile, ...)
    for row in reader:
        outfile.write(row[13] + ' 1:' + row[0] + ' 2:' + row[1])

Upvotes: 0

Related Questions