gpt4 book ai didi

python - 如果文件已经存在,如何防止 shutil.move 覆盖该文件?

转载 作者:行者123 更新时间:2023-12-01 23:59:38 24 4
gpt4 key购买 nike

我在 Windows 中使用此 Python 代码:

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

当此代码被多次调用时,它会覆盖目标文件。我想移动文件如果目的地已经存在,则重命名它

例如文件名 = foo.pdf

backup 文件夹中将是 foo.pdf, foo(1).pdf, foo(2).pdf 等或类似的,例如带破折号foo-1.pdf, foo-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)

或者由于这可能在循环中使用,您可以将其放入函数中。

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)

关于python - 如果文件已经存在,如何防止 shutil.move 覆盖该文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62064573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com