我试图将源目录中的每个csv文件及其子文件夹复制到一个新的“mega”文件夹中。最终结果将是一个文件夹,其中除了源目录中的csv文件外,什么也不包含
我面临的问题是,一些csv文件名是相同的。因此,在复制文件时,同名文件将被覆盖。我希望能够重命名它们,而不是覆盖它们。我想重命名文件的格式示例如下:
我找到了this thread,但答案对我不起作用
我的代码如下(基于提供的链接):
movdir = r"Source Directory"
basedir = r"Destination Folder"
# Walk through all files in the directory that contains the files to copy
for root, dirs, files in os.walk(movdir):
for filename in files:
# I use absolute path, case you want to move several dirs.
old_name = os.path.join(os.path.abspath(root), filename)
# Separate base from extension
base, extension = os.path.splitext(filename)
# Initial new name
new_name = os.path.join(basedir, base, filename)
# If folder basedir/base does not exist... You don't want to create it?
if not os.path.exists(os.path.join(basedir, base)):
print(os.path.join(basedir,base), "not found")
continue # Next filename
elif not os.path.exists(new_name): # folder exists, file does not
shutil.copy(old_name, new_name)
else: # folder exists, file exists as well
ii = 1
while True:
new_name = os.path.join(basedir,base, base + "_" + str(ii) + extension)
if not os.path.exists(new_name):
shutil.copy(old_name, new_name)
print("Copied", old_name, "as", new_name)
break
ii += 1
当我运行这段代码时,它只打印出源目录中的每个csv文件都是“未找到”的,并且没有任何文件被复制
如果您能提供任何帮助或信息,我们将不胜感激
尝试以下修改:
相关问题 更多 >
编程相关推荐