我有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
Path('nothing.txt').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())