Python: How to close my CSV input and output files?
嗨,我已经在此线程上试验Winston Ewert的代码示例。
Python:删除重复的CSV条目
但是我无法关闭我的输入和输出文件。 我究竟做错了什么?
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'
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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() for 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
1 2 3 4 | user, phone, email joe, 123, joe@x.com mary, 456, mary@x.com ed, 123, ed@x.com |
通过做:
1 | csv.reader(open('File1.csv', 'r')) |
您正在将匿名文件句柄传递给
1 | fr = open('File1.csv', 'r') |
和
1 | csv.reader(fr) |
然后
1 | fr.close() |
或使用上下文管理器:
1 2 | with open('File1.csv', 'r') as fr: csv.reader(fr) |
离开内容后,文件将被关闭
除了:在某些python版本上创建csv文件时,还有一个额外的陷阱。 使用