代碼:
import csv
with open(“test_write.csv”,‘w+’,encoding=‘utf-8’) as f:writer = csv.writer(f)
writer.writerow([“URL”,“predict”,“score”])
row = [[‘1’,1,1],[‘2’,2,2],[‘3’,3,3]]
for r in row:
writer.writerow ( r )
注:with open() as f 的好處是,若open()出現異常,會自動捕獲異常,且打開之後,自動關閉。
file= open(“test.txt”,“r”)
try:
for line in file.readlines():
print line
except:
print “error”
finally:
file.close()
即with的作用相當於try-except-finally