【问题标题】:How to copy found files如何复制找到的文件
【发布时间】:2019-10-21 05:51:47
【问题描述】:

下面程序的第一个函数效果很好,但是

  1. 不知道如何在第二个函数中调用第一个并将其结果复制到新目录中。

  2. 如何在不同的行中打印第一个函数中找到的文件? (每个文件一行)

谢谢。

# Write a program that walks through a folder tree and searches for files with
# a certain file extension (such as .pdf or .jpg). Copy these files from whatever
# location they are in to a new folder.


import os, shutil, fnmatch


def find_all(pattern, path):
    result = []
    for root, dirs, files in os.walk(path):
        for name in files:
            if fnmatch.fnmatch(name, pattern):
                result.append(os.path.join(root, name))
    return result


print(find_all('*.jpg', 'D:\\firstfolder'))


# Copy the found files into another directory
def found_files(dst):
    dst = os.chdir('D:\\secondfolder')
    for files in find_all():
        shutil.copytree(dst)


found_files(dst)

【问题讨论】:

    标签: python function copy shutil


    【解决方案1】:

    您缺少函数参数。应该是这样的

    def founded_files(dst):
        dst = os.chdir('D:\\secondfolder')
        for files in find_all('*.jpg', 'D:\\firstfolder'):
            shutil.copytree(dst)
    

    【讨论】:

    • 但我得到一个错误:NameError: name 'dst' is not defined.
    • 不知道os.chdir的返回值。也许只使用shutil.copytree('D:\\secondfolder')
    猜你喜欢
    • 2016-09-20
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 2010-11-02
    相关资源
    最近更新 更多