![](/img/trans.png)
[英]PermissionError: when using os.remove and os.rename in a loop in python
[英]Is it wise to remove files using os.rename() instead of os.remove() in Python?
我有一個名為fin
的文件,需要修改。
在Python中,我創建了一個腳本,進行所需的修改,然后將其保存在名為fout
新文件中。
較舊的文件對我無用,因此我使用os.remove('fin')
刪除了它。 但是,修改后的文件應命名為fin
,因此我使用os.rename('fout','fin')
。
我想到了一個使用os.rename('fout','fin')
的快捷方式,因為它是同一個名稱,所以期望它刪除fin
,但是我不確定這是否實際上是在刪除舊文件或如果多次執行此操作可能會造成一些麻煩(執行此任務超過1000次)。
我的問題是:這是實現這一目標的最干凈,最快的方法嗎? 總之,我只想在原始文件中進行更正並覆蓋它。
碼:
import os
f = open('fin','w')
f.write('apples apple apples\napple apples apple\napples apple apples')
f.close()
with open('fin', 'rt') as fin:
with open('fout', 'wt') as fout:
for line in fin:
fout.write(line.replace('apples', 'orange'))
os.rename('fout', 'fin')
您的模式可以在POSIX系統上使用,但不能在Windows上使用。 我建議使用os.replace
以OS不可知的方式替換現有文件。 它要求使用Python 3.3或更高版本,但是無論如何,新代碼通常應該以Python 3為目標。
這是首選模式,因為它可以保證原子性。 fin
文件之前或之后始終處於完整狀態,沒有失敗的風險,導致文件處於部分/損壞狀態。
從您的示例看來,您似乎沒有理由逐行遍歷文件。 如果是這樣,這是一個非常簡單的解決方案。
f = open('fin','w').write('apples apple apples\napple apples apple\napples apple apples')
s = open('fin').read().replace('apples', 'oranges')
open('fin','w').write(s)
為了實現交叉兼容性,我建議您將with代碼反轉。 我的建議代碼是
f = open('fin','w')
f.write('apples apple apples\napple apples apple\napples apple apples')
f.close()
with open('fout', 'wt') as fout:
with open('fin', 'rt') as fin:
for line in fin.readlines():
fout.write(line.replace('apples', 'orange'))
os.unlink('fin')
os.rename('fout', 'fin')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.