3 回答

TA貢獻1818條經驗 獲得超11個贊
如果文件已經存在,我們要創建一個新文件而不是覆蓋它。
for filname in filelistsrc:
if os.path.exists(dictfiles[filename]):
i, temp = 1, filename
file_name, ext = filename.split("/")[-1].split(".")
while os.path.exists(temp):
temp = os.path.join(strdest, f"{file_name}_{i}.{ext}")
dictfiles[filename] = temp
i += 1
shutil.move(filename, dictfiles[filename])
檢查目的地是否存在。如果是,請創建一個新目標并移動文件。

TA貢獻1780條經驗 獲得超5個贊
在最后一個 for 循環中移動它之前,您可以檢查文件是否已經存在,并取決于移動它的結果。我做了一個遞歸函數來檢查文件名并遞增它直到文件名是新的:
import os
def renamefile(ffpath, idx = 1):
#Rename the file from test.jpeg to test1.jpeg
path, ext = os.path.splitext(ffpath)
path, filename = path.split('/')[:-1], path.split('/')[-1]
new_filename = filename + str(idx)
path.append(new_filename + ext)
path = ('/').join(path)
#Check if the file exists. if not return the filename, if it exists increment the name with 1
if os.path.exists(path):
print("Filename {} already exists".format(path))
return renamefile(ffpath, idx = idx+1)
return path
for filename in filelistsrc:
if os.path.exists(filename):
renamefile(filename)
shutil.move(filename, dictfiles[filename])

TA貢獻1846條經驗 獲得超7個贊
這是另一個解決方案,
def move_files(str_src, str_dest):
for f in os.listdir(str_src):
if os.path.isfile(os.path.join(str_src, f)):
# if not .html continue..
if not f.endswith(".html"):
continue
# count file in the dest folder with same name..
count = sum(1 for dst_f in os.listdir(str_dest) if dst_f == f)
# prefix file count if duplicate file exists in dest folder
if count:
dst_file = f + "_" + str(count + 1)
else:
dst_file = f
shutil.move(os.path.join(str_src, f),
os.path.join(str_dest, dst_file))
添加回答
舉報