简体   繁体   English

如何通过更改名称覆盖文件?

[英]How can I overwrite a file by changing name?

I have something.txt and nothing.txt .我有something.txtnothing.txt How can I change the name of nothing.txt to something.txt and at the same time remove the old something.txt ?如何将nothing.txt的名称更改为something.txt并同时删除旧的something.txt

You can check if the first file exist.您可以检查第一个文件是否存在。 And if it does, remove it first.如果是这样,请先将其删除。

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)

Using pathlib is easier.使用pathlib更容易。 It is just .rename这只是.rename

from pathlib import Path

nothing = Path('nothing.txt')
nothing.rename('something.txt')

Demo Script演示脚本

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM