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:文件的缩进,文件就会自动关闭。
添加回答
举报
