我导入了os
和shutil
模块来完成此任务。但是当我使用os.path.join root_dir with fi_name
存储源文件时,它会给出以下错误消息:
无法将str与列表类型连接
如何完成此任务?
答案 0 :(得分:0)
此代码会将当前目录和当前目录的子目录中的所有文件移动到名为`sub_folder的新子目录中。
import os
new_folder_name = 'sub_folder'
base_path = os.getcwd()
new_folder_add = os.path.join(base_path, new_folder_name)
if not os.path.isdir(new_folder_add):
os.mkdir(new_folder_name)
walk = os.walk(base_path)
for level in walk:
if level[0] == new_folder_add:
continue
for fname in level[2]:
file_add = os.path.join(level[0], fname)
new_file_add = os.path.join(new_folder_add, fname)
# this will replace if there exists an other file with new_file_add address
os.rename(file_add, new_file_add)