簡體   English   中英

如何通過更改名稱覆蓋文件?

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

我有something.txtnothing.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM