Python复制文件忽略树结构

2024-10-03 09:21:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将文件从一个目录及其子目录复制到一个唯一的目标目录,而不需要复制源目录的树结构(这意味着将文件混合在一起)。你知道吗

#!/usr/bin/python 
# -*- coding: utf-8 -*- 

import os
import shutil

src  = '/Users/wiltomap/Desktop/depart/paquet'
dest = '/Users/wiltomap/Desktop/arrivee'

for dir, subdir, files in os.walk(src):
    for f in files:
        shutil.copy(f, dest)

…代码不起作用!以下是我在终端中运行它得到的信息:

IOError: [Errno 2] No such file or directory: 'paquet1.rtf'

“paquet1.rtf”是存在于子目录“/paquet/paquet1/”中的文件。你知道吗

谢谢你的帮助!你知道吗


Tags: 文件inimportsrcforosfilesusers
1条回答
网友
1楼 · 发布于 2024-10-03 09:21:00

所以也许像是…:

for dir, subdir, files in os.walk(src):
    for f in files:
        targ = os.path.join(dest, f)
        if os.path.exists(targ):
            for i in itertools.count():
                targ = os.path.join(dest, '%s(%s)' % (f, i))
                if not os.path.exists(targ):
                    break
        shutil.copy(os.path.join(dir, f), targ)

相关问题 更多 >