在Python中复制多个文件

hid*_*yat 78 python copy file

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

Gre*_*att 121

您可以使用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)
Run Code Online (Sandbox Code Playgroud)

  • @StevenByrne也可以,具体取决于您是否还要重命名该文件.如果没有,那么`dest`就是目录名.`shutil.copy(src,dst)`"将文件src复制到文件或目录dst ....如果dst指定了一个目录,该文件将使用src中的基本文件名复制到dst中." (3认同)

Ste*_*ven 27

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

for filename in glob.glob(os.path.join(source_dir, '*.*')):
    shutil.copy(filename, dest_dir)
Run Code Online (Sandbox Code Playgroud)

  • 注意:您可能必须使用os.path.isfile()检查glob结果,以确保它们是文件名.另见GreenMatt的回答.虽然glob确实只返回像os.listdir这样的文件名,但它仍然会返回目录名.只要您没有无扩展名的文件名或目录名称中的点,'*.*'模式就足够了. (2认同)

Doo*_*oon 11

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

  • 从Python 3.8开始 (5认同)
  • @Sven 为此尝试 `dirs_exist_ok=True` 选项。 (3认同)
  • 好的评论,但如果目录因某种原因已经存在,可能不是一个选项,就像我的情况一样. (2认同)

小智 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)
Run Code Online (Sandbox Code Playgroud)


小智 5

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
Run Code Online (Sandbox Code Playgroud)