2 回答
TA貢獻1802條經驗 獲得超6個贊
試試這個方法
import csv
with open('abbreviations.csv', mode='r') as infile:
reader = csv.reader(infile)
with open('abbreviations_new.csv', mode='w') as outfile:
writer = csv.writer(outfile)
mydict = {rows[0]:rows[1] for rows in reader}
print(len(mydict))
print(mydict['v'])
mydict['MIS'] = 'Management Information System'
print(mydict['TA'])
mydict['TA'] = 'teaching assistant'
print(mydict['TA'])
print(mydict['flower'])
del mydict['flower']
當您使用 with open 時,循環結束時文件會自動關閉。
TA貢獻1865條經驗 獲得超7個贊
您可以使用
with open('abbreviations.csv', mode='r') as infile, open( # you can put two opens after
'abbreviations_new.csv', mode='w') as outfile: # one with statement
reader = csv.reader(infile)
writer = csv.writer(outfile)
mydict = {rows[0]:rows[1] for rows in reader}
print(len(mydict))
print(mydict['v'])
mydict['MIS'] = 'Management Information System'
print(mydict['TA'])
mydict['TA'] = 'teaching assistant'
print(mydict['TA'])
print(mydict['flower'])
del mydict['flower']
# on this indentation level the files are closed
一旦您離開with open(...) as f:文件的縮進,文件就會自動關閉。
添加回答
舉報
