我正在尝试在Windows中移动文件。当前文件位于驱动器C:下的文件夹中,但我想将它们移动到驱动器D:中的某个位置
我正在使用shutil.move函数,但如果文件存在,该函数将覆盖该文件。我希望在目标中保留文件的副本,而不是覆盖它。有这样的功能吗
def movefiles(strsrc, strdest, strextension):
filelistsrc = [] #source files full path
# store the destination of the current file
dictfiles = {}
for f in os.listdir(strsrc):
if os.path.isfile(os.path.join(strsrc, f)):
filefullname = os.path.join(strsrc, f)
if filefullname.endswith(".html"):
filelistsrc.append(filefullname)
dictfiles[filefullname] = os.path.join(strdest, f)
if not filelistsrc:
return -1
print("Start moving files from:")
printstrlist(filelistsrc)
for filename in filelistsrc:
shutil.move(filename, dictfiles[filename])
return 0
在最后一个for循环中移动文件之前,您可以检查文件是否已经存在,并根据移动结果进行检查。我制作了一个递归函数,用于检查文件名并递增,直到文件名是新的:
如果文件已经存在,我们希望创建一个新文件,而不是覆盖它
检查目的地是否存在。如果是,请创建新目标并移动文件
这是另一个解决方案
相关问题 更多 >
编程相关推荐