Python 3.4 查找所有文件类型并复制到目录

Python 3.4 Find all file types and copy to directory

我正在尝试创建一个备份程序来查找目录和子目录中的所有 txt 文件并将其复制到另一个目录。我是 python 的新手,尝试过使用 glob 和 shutil 模块。我将我的路径添加到变量以使它们更容易更改。

import os
import shutil

src= "C:/"
dest= "F:/newfolder"

src_files = os.listdir(src)
for file in src:
    filename = os.path.join(src, file)
    if file.endswith(".txt"):
        shutil.copy(file, dest)

使用这个脚本。 它将所有文本文件从 src 复制到 dest 目录(dest 是一个现有目录)

import os, shutil

def copy(src, dest):
    for name in os.listdir(src):
        pathname = os.path.join(src, name)
        if os.path.isfile(pathname):
            if name.endswith('.txt'):
                shutil.copy2(pathname, dest)      
        else:
            copy(pathname, dest)

copy(src, dest)

如果你需要得到相同的目录树,使用这个:

def copy(src, dest):
    for name in os.listdir(src):
        pathname = os.path.join(src, name)
        if os.path.isfile(pathname):        
            if name.endswith('.txt'):
                if not os.path.isdir(dest):
                    os.makedirs(dest)
                shutil.copy2(pathname, dest)      
        else:
            copy(os.path.join(src, name), os.path.join(dest, name))

您有:for file in src:您是说 for file in src_files: 吗?

试试这个:

import glob, os, shutil

files = glob.iglob(os.path.join(source_dir, "*.txt"))
for file in files:
    if os.path.isfile(file):
        shutil.copy2(file, dest_dir)

从 Python 3.4 开始有新模块 pathlib 可以遍历目录和子目录。 一种可能的方法来做你需要的是创建吐出所有 txt 文件的生成器。迭代生成器并使用 shutil 进行复制。

from pathlib import Path
import shutil

src= "C:/"
dest= "F:/newfolder"

generator = (str(f) for f in Path(src).iterdir() if f.is_file() and f.suffix=='.txt')

for item in generator:
    shutil.copy2(item, dest)

另一个基于你们输入的解决方案:只需编辑 src 目标并添加 "recursive-True" - 然后它完美运行。

import glob, os, shutil

src= "E:/Work/**/"
dest= "E:/Private"

files = glob.iglob(os.path.join(src, "*string that is searched in name of files*"),recursive=True)
for file in files:
    if os.path.isfile(file):
        shutil.copy2(file, dest)