在Python中处理文件从源目录到目标目录

2 投票
3 回答
1598 浏览
提问于 2025-04-15 21:20

作为一个对 Python 完全陌生 的新手,我想在一组文件上运行一个命令。这个命令需要指定源文件和目标文件(实际上,我在下面的例子中使用的是 imagemagick 的 convert 命令)。

我可以提供源目录和目标目录,但我不知道怎么简单地保持源目录到目标目录的结构。

比如说,假设 srcdir 里面有以下内容:

srcdir/
   file1
   file3
   dir1/
       file1
       file2

然后我希望程序在 destdir 中创建以下目标文件: destdir/file1destdir/file3destdir/dir1/file1destdir/dir1/file2

到目前为止,我想到的办法是:

import os
from subprocess import call

srcdir = os.curdir # just use the current directory
destdir = 'path/to/destination'

for root, dirs, files in os.walk(srcdir):
    for filename in files:
        sourceFile = os.path.join(root, filename)
        destFile = '???'
        cmd = "convert %s -resize 50%% %s" % (sourceFile, destFile)
        call(cmd, shell=True)

但是,walk 方法并没有直接告诉我文件在 srcdir 下的具体目录,只能通过把根目录的字符串和文件名拼接在一起。有没有什么简单的方法可以得到目标文件,还是说我必须进行一些字符串处理才能做到这一点?

3 个回答

0

虽然这个方法看起来不太美观,但它能保持文件夹树的结构:

_, _, subdirs = root.partition(srcdir)
destfile = os.path.join(destdir, subdirs[1:], filename)
1

有一些脚本可以帮助你找到两个路径之间的相对路径,也就是你想要的功能。比如:

可惜的是,我觉得这个功能从来没有被加入到Python的核心库中。

2

把你的循环改成这样:

for root, dirs, files in os.walk(srcdir):
    destroot = os.path.join(destdir, root[len(srcdir):])
    for adir in dirs:
        os.makedirs(os.path.join(destroot, adir))
    for filename in files:
        sourceFile = os.path.join(root, filename)
        destFile = os.path.join(destroot, filename)
        processFile(sourceFile, destFile)

撰写回答