2017-08-20 375 views
1

嗨,我一直在試驗Winston Ewert的代碼示例從這個線程。Python:如何關閉我的CSV輸入和輸出文件?

Python: Removing duplicate CSV entries

但我不能收我的輸入和輸出文件。我究竟做錯了什麼?

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() 

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

user, phone, email 
joe, 123, [email protected] 
mary, 456, [email protected] 
ed, 123, [email protected] 
+0

你爲什麼不能關閉它們?你遇到了什麼錯誤?你爲什麼評論結束語? –

回答

4

通過執行:

csv.reader(open('File1.csv', 'r')) 

你傳遞一個匿名文件句柄csv.reader對象,因此當文件將被關閉,你無法控制(這是這個句柄需要被關閉,而不是csv.reader對象)

close方法必須適用於文件句柄(CSV讀/寫器對象可以在列表上工作,迭代器......,他們不能有close方法),所以我會做:

fr = open('File1.csv', 'r') 

csv.reader(fr) 

然後

fr.close() 

或使用上下文管理器:

with open('File1.csv', 'r') as fr: 
    csv.reader(fr) 

和文件將盡快離開上下文

除了關閉:有當創建一個額外的抓一些python版本的csv文件。使用類似open('File2.csv', 'w')的手柄可能會導致問題(插入空白行)。對於兼容的&健壯的方式,你可以閱讀this Q&A