如何通过Python编码将所有数据文件从许多文件夹移至其子文件夹?

时间:2018-12-03 15:44:03

标签: python-2.7

我导入了osshutil模块来完成此任务。但是当我使用os.path.join root_dir with fi_name存储源文件时,它会给出以下错误消息:

  

无法将str与列表类型连接

如何完成此任务?

1 个答案:

答案 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)