簡體   English   中英

如果文件已經存在,如何防止 shutil.move 覆蓋該文件?

[英]How to prevent shutil.move from overwriting a file if it already exists?

我在Windows中使用這個Python代碼:

shutil.move(documents_dir + "\\" + file_name, documents_dir + "\\backup\\"
            + subdir_name + "\\" + file_name)

當多次調用此代碼時,它會覆蓋目標文件。 我想移動文件,如果目標已經存在,重命名它

例如file_name = foo.pdf

backup文件夾中將是foo.pdffoo(1).pdffoo(2).pdf等或類似的破折號foo-1.pdffoo-2.pdf等。

您可以邊走邊檢查os.path.exists()

import os
import shutil

file_name = 'test.csv'
documents_dir = r'C:\BR\Test'
subdir_name = 'test'

# using os.path.join() makes your code easier to port to another OS
source = os.path.join(documents_dir, file_name)
dest = os.path.join(documents_dir, 'backup', subdir_name, file_name)

num = 0
# loop until we find a file that doesn't exist
while os.path.exists(dest):
    num += 1

    # use rfind to find your file extension if there is one
    period = file_name.rfind('.')
    # this ensures that it will work with files without extensions
    if period == -1:
        period = len(file_name)

    # create our new destination
    # we could extract the number and increment it
    # but this allows us to fill in the gaps if there are any
    # it has the added benefit of avoiding errors 
    # in file names like this "test(sometext).pdf"
    new_file = f'{file_name[:period]}({num}){file_name[period:]}'

    dest = os.path.join(documents_dir, 'backup', subdir_name, new_file)

shutil.move(source, dest)

或者由於這可能在循環中使用,您可以將其放入 function。

import os
import shutil

def get_next_file(file_name, dest_dir):
    dest = os.path.join(dest_dir, file_name)
    num = 0

    while os.path.exists(dest):
        num += 1

        period = file_name.rfind('.')
        if period == -1:
            period = len(file_name)

        new_file = f'{file_name[:period]}({num}){file_name[period:]}'

        dest = os.path.join(dest_dir, new_file)

    return dest

file_name = 'test.csv'
documents_dir = r'C:\BR\Test'
subdir_name = 'test'

source = os.path.join(documents_dir, file_name)

dest = get_next_file(file_name, os.path.join(documents_dir, 'backup', subdir_name))

shutil.move(source, dest)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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