如何解决将目录中的所有文件复制到新目录中,同时在Python中重命名具有相同名称的文件
我正在尝试将源目录中的每个csv文件及其子文件夹复制到新的“ mega”文件夹中。最终结果将是一个文件夹,除了在源目录中找到的csv文件之外,什么都不包含。
我遇到的问题是某些csv文件名相同。因此,在复制文件时,具有相同名称的文件将被覆盖。我希望能够重命名它们,而不是覆盖它们。我想重命名文件的格式的示例是:
- abcd
- abcd_1
- abcd_2,等等...
我找到了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 + "_" + 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文件都是“未找到”的,并且没有任何文件被复制。
任何帮助或信息,将不胜感激。
解决方法
尝试以下修改:
args = list("visible",list(T,T,F,F))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。