Python: How to close my CSV input and output files? -
hi have been experimenting winston ewert's code example thread.
python: removing duplicate csv entries
but can't close input , output files. doing wrong?
write_outfile.close()
write_infile.close()
traceback (most recent call last): file "duplicates_01.py", line 26, in write_outfile.close() attributeerror: '_csv.writer' object has no attribute 'close'
import csv write_infile = csv.reader(open('file1.csv', 'r')) write_outfile = csv.writer(open('file2.csv', 'w')) #write_infile = open('file1.csv', 'r') #f1 = csv.reader(write_infile) #f1 = csv.reader(write_infile, delimiter=' ') #write_outfile = open('file2.csv', 'w') #f2 = csv.writer(write_outfile) #f2 = csv.writer(write_outfile, delimiter=' ') phone_numbers = set() row in write_infile: if row[1] not in phone_numbers: write_outfile.writerow(row) # f2.writerow(row) phone_numbers.add(row[1]) # write_outfile.close() # write_infile.close()
file1.csv
user, phone, email joe, 123, joe@x.com mary, 456, mary@x.com ed, 123, ed@x.com
by doing:
csv.reader(open('file1.csv', 'r'))
you're passing anonymous file handle csv.reader
objects, cannot control when file closed (it's handle needs closed, not csv.reader
object)
the close
method must apply file handle (csv reader/writer objects can work on lists, iterators, ..., can't have close
method) do:
fr = open('file1.csv', 'r')
and
csv.reader(fr)
then
fr.close()
or use context manager:
with open('file1.csv', 'r') fr: csv.reader(fr)
and file closed leave context
aside: there's catch when creating csv files on python versions. using handle open('file2.csv', 'w')
may cause problems (blank lines inserted). compatible & robust way can read this q&a
Comments
Post a Comment