使用Python处理从源目录到目标目录的一组文件 [英] Process a set of files from a source directory to a destination directory in Python

查看:134
本文介绍了使用Python处理从源目录到目标目录的一组文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

成为python中的全新我正在尝试对python中的一组文件运行命令.该命令需要源文件和目标文件(实际上我正在使用imagemagick convert,如下面的示例所示).

Being completely new in python I'm trying to run a command over a set of files in python. The command requires both source and destination file (I'm actually using imagemagick convert as in the example below).

我可以提供源目录和目标目录,但是我不知道如何轻松地保留从源目录到目标目录的目录结构.

I can supply both source and destination directories, however I can't figure out how to easily retain the directory structure from the source to the destination directory.

例如说srcdir包含以下内容:

srcdir/
   file1
   file3
   dir1/
       file1
       file2

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

Then I want the program to create the following destination files on destdir: destdir/file1, destdir/file3, destdir/dir1/file1 and destdir/dir1/file2

到目前为止,这是我想出的:

So far this is what I came up with:

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下的目录,而是将根目录字符串与文件名连接在一起.是否有一些简单的方法来获取目标文件,或者我必须做一些字符串操作才能做到这一点?

The walk method doesn't directly provide what directory the file is under srcdir other than concatenating the root directory string with the file name. Is there some easy way to get the destination file, or do I have to do some string manipulation in order to do this?

推荐答案

将循环更改为:

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)

这篇关于使用Python处理从源目录到目标目录的一组文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆