为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

元芳怎么了 2021-12-29 10:31:29
我相信这一切都与缩进有关,但我不确定如何准确缩进,请帮助我。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']
查看完整描述

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 时,循环结束时文件会自动关闭。


查看完整回答
反对 回复 2021-12-29
?
鸿蒙传说

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:文件的缩进,文件就会自动关闭。


查看完整回答
反对 回复 2021-12-29
  • 2 回答
  • 0 关注
  • 248 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号