在 Python 中复制多个文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3397752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:50:46  来源:igfitidea点击:

Copy multiple files in Python

pythonfilecopy

提问by hidayat

How to copy all the files present in one directory to another directory using Python. I have the source path and the destination path as string.

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

采纳答案by GreenMatt

You can use os.listdir()to get the files in the source directory, os.path.isfile()to see if they are regular files (including symbolic links on *nix systems), and shutil.copyto do the copying.

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

The following code copies only the regular files from the source directory into the destination directory (I'm assuming you don't want any sub-directories copied).

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

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)

回答by Doon

Look at shutil in the Python docs, specifically the copytreecommand.

查看Python 文档中shutil,特别是copytree命令。

回答by Steven

If you don't want to copy the whole tree (with subdirs etc), use or glob.glob("path/to/dir/*.*")to get a list of all the filenames, loop over the list and use shutil.copyto copy each file.

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

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

回答by Isaac Ewhuiknebueze

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)

回答by Константин Бушко

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

回答by Dustin Michels

Here is another example of a recursive copy function that lets you copy the contents of the directory (including sub-directories) one file at a time, which I used to solve this problem.

这是递归复制功能的另一个示例,它可以让您一次一个文件复制目录(包括子目录)的内容,我用它来解决这个问题。

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)

EDIT:If you can, definitely just use shutil.copytree(src, dest). This requires that that destination folder does not already exist though. If you need to copy files into an existing folder, the above method works well!

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