[英]How can I overwrite a file by changing name?
我有something.txt
和nothing.txt
。 如何將nothing.txt
的名稱更改為something.txt
並同時刪除舊的something.txt
?
您可以檢查第一個文件是否存在。 如果是這樣,請先將其刪除。
from os import path, rename, remove
def mv(source, destination, overwrite=True):
if path.isfile(destination):
if overwrite:
remove(destination)
else:
raise IOError("Destination file already exist")
rename(source, destination)
使用pathlib
更容易。 這只是.rename
from pathlib import Path
nothing = Path('nothing.txt')
nothing.rename('something.txt')
from pathlib import Path
# create file and populate with text for demo
with Path('something.txt').open('w') as f:
f.write('something old!')
# check contents
print(Path('something.txt').open('r').readline())
nothing = Path('nothing.txt')
with nothing.open('w') as f:
f.write('something new!')
# rename replaces the old something with new
nothing.rename('something.txt')
# check results
print(Path('something.txt').open('r').readline())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.