2 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超6個(gè)贊
試試這個(gè)方法
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']
當(dāng)您使用 with open 時(shí),循環(huán)結(jié)束時(shí)文件會(huì)自動(dòng)關(guān)閉。

TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
您可以使用
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:文件的縮進(jìn),文件就會(huì)自動(dòng)關(guān)閉。
添加回答
舉報(bào)