猿问

PYTHON:关闭文件的 I/O 操作

我相信这一切都与缩进有关,但我不确定如何准确缩进,请帮助我。


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']


元芳怎么了
浏览 249回答 2
2回答

呼啦一阵风

试试这个方法import csvwith 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 时,循环结束时文件会自动关闭。

鸿蒙传说

您可以使用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:文件的缩进,文件就会自动关闭。
随时随地看视频慕课网APP

相关分类

Python
我要回答