我需要从大约十二个子文件夹中复制多个.mp4和.CR2文件。我尝试了多种代码,并希望从头开始。
import os
import shutil
#os.chdir('C:\\')
dir_src = 'D:\\Users\\Tibi\\Pictures'
dir_dst = 'D:\\test'
#while True:
# try:
# for folder in os.walk(dir_src):
# print(folder)
# for filename in os.listdir(dir_src):
# if filename.endswith('.CR2'):
# shutil.copy(dir_src + '\\' + filename, dir_dst)
# print(filename)
# except UnicodeEncodeError:
# print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>File %s was Skipped!<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" %filename)
import pathlib
import glob
dir_src = pathlib.Path('D:\\Users\\Tibi\\Pictures\\Move')
dir_dst = pathlib.Path('D:\test')
for file in dir_src.rglob('*.CR2'):
shutil.copy(dir_src + '\\' + file, dir_dst)
print("Current File is: %s" % file)
我已经尝试过没有代码的注释掉的代码。
答案 0 :(得分:1)
这应该做你想要的,但它确实假设没有文件具有相同的名称:
import os
import shutil
source_dir = r"/Users/ThatOtherBatman/Foo/"
target_dir = r"/Users/ThatOtherBatman/Bar/"
extensions = (".mp4", ".cr2")
for directory, _, file_names in os.walk(source_dir):
for file_name in file_names:
if file_name.lower().endswith(extensions):
source_path = os.path.join(directory, file_name)
target_path = os.path.join(target_dir, file_name)
print("Moving {} to {}".format(file_name, target_dir))
shutil.copy(source_path, target_dir)
os.walk
是您希望用于递归搜索目录的内容。然后,检查文件扩展名是否在您想要的扩展名中,如果是,则复制该文件。