這個問題在這里已經有了答案: 在 Python 檔案物件上使用迭代器時是否需要 close() [重復] (8 個回答) 16 小時前關閉。
來源
import os, re
directory = os.listdir('C:/foofolder8')
os.chdir('C:/foofolder8')
for file in directory:
open_file = open(file,'r')
read_file = open_file.read()
regex = re.compile('jersey')
read_file = regex.sub('york', read_file)
write_file = open(file, 'w')
write_file.write(read_file)
該腳本將所有檔案中的“jersey”替換C:/foofolder8為“york”。我用檔案夾中的三個檔案進行了嘗試,并且可以正常作業。訊息來源指出,“您可能會在最后一個檔案中發現錯誤”,我確實遇到了這種情況——最后一個檔案中的所有文本都被簡單地洗掉了。
為什么腳本會為最后一個檔案中斷?只有最后一個檔案中斷這一事實使得for回圈似乎有問題,但我看不出有什么問題。呼叫directory顯示目錄下也有3個檔案,是正確的。
uj5u.com熱心網友回復:
嘗試:
import os, re
directory = os.listdir('C:/foofolder8')
os.chdir('C:/foofolder8')
for file in directory:
with open(file,'r') as open_file:
read_file = open_file.read()
regex = re.compile('jersey')
read_file = regex.sub('york', read_file)
with open (file, 'w') as write_file:
write_file.write(read_file)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/371038.html
下一篇:反向串列并將其附加到istelf
