亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 245 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號