我不想测试将要移动的文件的名称,看我们是否已经在目标目录中。相反,此解决方案只扫描目标的子目录import os
import itertools
import shutil
def move(destination):
all_files = []
for root, _dirs, files in itertools.islice(os.walk(destination), 1, None):
for filename in files:
all_files.append(os.path.join(root, filename))
for filename in all_files:
shutil.move(filename, destination)
说明:os.walk以“自顶向下”的方式递归地遍历目的地。整个文件名是用os.path.join(root,filename)调用构造的。现在,为了防止扫描目标顶部的文件,我们只需要忽略os.walk迭代的第一个元素。为此,我使用islice(iterator,1,None)。另一个更明确的方法是:def move(destination):
all_files = []
first_loop_pass = True
for root, _dirs, files in os.walk(destination):
if first_loop_pass:
first_loop_pass = False
continue
for filename in files:
all_files.append(os.path.join(root, filename))
for filename in all_files:
shutil.move(filename, destination)