[英]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.