我有something.txt和nothing.txt。如何更改名稱nothing.txt以something.txt,并在同一時間洗掉舊的something.txt?
uj5u.com熱心網友回復:
您可以檢查檔案是否存在。如果是這樣,請先將其洗掉。
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)
uj5u.com熱心網友回復:
使用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())
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/334138.html
上一篇:將字典寫入檔案,從檔案中檢索字典
下一篇:如何從檔案中讀取特殊字符?
