【问题标题】:Copy multiple files in Python在 Python 中复制多个文件
【发布时间】:2011-03-24 18:55:43
【问题描述】:

如何使用 Python 将一个目录中的所有文件复制到另一个目录。 我将源路径和目标路径作为字符串。

【问题讨论】:

标签: python file copy


【解决方案1】:

您可以使用os.listdir() 获取源目录中的文件,os.path.isfile() 来查看它们是否是常规文件(包括 *nix 系统上的符号链接),并使用 shutil.copy 进行复制。

以下代码仅将常规文件从源目录复制到目标目录(我假设您不希望复制任何子目录)。

import os
import shutil
src_files = os.listdir(src)
for file_name in src_files:
    full_file_name = os.path.join(src, file_name)
    if os.path.isfile(full_file_name):
        shutil.copy(full_file_name, dest)

【讨论】:

  • 应该是 C:\myfolder 或 C:\myfolder\filename.ext 之类的东西?
  • @StevenByrne 可以是任何一个,具体取决于您是否还想重命名文件。如果不是,则 dest 是目录名称。 shutil.copy(src, dst) "将文件 src 复制到文件或目录 dst.... 如果 dst 指定目录,则文件将使用 src 中的基本文件名复制到 dst。"
  • 小改进:离开 src_files 并做for fn in os.listdir(src)
【解决方案2】:

如果您不想复制整个树(带有子目录等),请使用或glob.glob("path/to/dir/*.*") 来获取所有文件名的列表,遍历列表并使用shutil.copy 来复制每个文件。

for filename in glob.glob(os.path.join(source_dir, '*.*')):
    shutil.copy(filename, dest_dir)

【讨论】:

  • 注意:您可能必须使用 os.path.isfile() 检查 glob 结果以确保它们是文件名。另请参阅 GreenMatt 的回答。虽然 glob 只返回像 os.listdir 这样的文件名,但它仍然返回目录名。 '.' 模式可能就足够了,只要您没有无扩展名的文件名或目录名中的点。
  • 这不会复制子目录
【解决方案3】:

查看shutil in the Python docs,特别是copytree 命令。

如果目标目录已经存在,请尝试:

shutil.copytree(source, destination, dirs_exist_ok=True)

【讨论】:

  • 说得好,但如果目录由于某种原因已经存在,就像我的情况一样,它可能不是一个选项。
  • @Sven 为此尝试dirs_exist_ok=True 选项。
  • 从 Python 3.8 开始
【解决方案4】:
def recursive_copy_files(source_path, destination_path, override=False):
    """
    Recursive copies files from source  to destination directory.
    :param source_path: source directory
    :param destination_path: destination directory
    :param override if True all files will be overridden otherwise skip if file exist
    :return: count of copied files
    """
    files_count = 0
    if not os.path.exists(destination_path):
        os.mkdir(destination_path)
    items = glob.glob(source_path + '/*')
    for item in items:
        if os.path.isdir(item):
            path = os.path.join(destination_path, item.split('/')[-1])
            files_count += recursive_copy_files(source_path=item, destination_path=path, override=override)
        else:
            file = os.path.join(destination_path, item.split('/')[-1])
            if not os.path.exists(file) or override:
                shutil.copyfile(item, file)
                files_count += 1
    return files_count

【讨论】:

  • 对您的代码进行口头解释会有所帮助
  • 我想你的意思是 overwrite,而不是 override
  • 康斯坦丁很好的答案!帮了我很多。不过有一个建议:使用 os.sep 而不是 '/' (因此它适用于非 Linux 操作系统)
【解决方案5】:
import os
import shutil
os.chdir('C:\\') #Make sure you add your source and destination path below

dir_src = ("C:\\foooo\\")
dir_dst = ("C:\\toooo\\")

for filename in os.listdir(dir_src):
    if filename.endswith('.txt'):
        shutil.copy( dir_src + filename, dir_dst)
    print(filename)

【讨论】:

    【解决方案6】:

    这是递归复制函数的另一个示例,它允许您一次复制一个文件的目录(包括子目录)的内容,我用它来解决这个问题。

    import os
    import shutil
    
    def recursive_copy(src, dest):
        """
        Copy each file from src dir to dest dir, including sub-directories.
        """
        for item in os.listdir(src):
            file_path = os.path.join(src, item)
    
            # if item is a file, copy it
            if os.path.isfile(file_path):
                shutil.copy(file_path, dest)
    
            # else if item is a folder, recurse 
            elif os.path.isdir(file_path):
                new_dest = os.path.join(dest, item)
                os.mkdir(new_dest)
                recursive_copy(file_path, new_dest)
    

    编辑:如果可以,请务必使用shutil.copytree(src, dest)。这要求该目标文件夹不存在。如果您需要将文件复制到现有文件夹中,上述方法效果很好!

    【讨论】:

    • 正是我需要的,递归复制子目录的东西,谢谢!
    【解决方案7】:

    评分最高的答案将引发运行时错误,因为它试图在第 5 行加入带有文件名的列表,而它本应将一个字符串与另一个字符串连接起来。创建另一个名为 pathSrc 的变量并在 join 参数中使用它。我还将创建另一个名为 pathDest 的变量,并将其与最后一行的 file_name 连接起来。我还从shutil而不是整个模块导入了所需的方法。

    import os
    from shutil import copyfile
    pathSrc = "the folder where the src files are"
    pathDest = "the folder where the dest files are going"
    src_files = os.listdir(src)
    for file_name in src_files:
        full_file_name = os.path.join(pathSrc, file_name)
        if os.path.isfile(full_file_name):
            shutil.copy(full_file_name, pathDest + file_name)
    

    【讨论】:

      猜你喜欢
      • 2017-11-29
      • 1970-01-01
      • 2013-08-11
      • 2019-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-13
      • 1970-01-01
      相关资源
      最近更新 更多