Process a set of files from a source directory to a destination directory in Python

Posted by Spoike on Stack Overflow See other posts from Stack Overflow or by Spoike
Published on 2010-04-07T14:45:51Z Indexed on 2010/04/07 15:23 UTC
Read the original article Hit count: 163

Filed under:
|

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.

E.g. say the srcdir contains the following:

srcdir/
   file1
   file3
   dir1/
       file1
       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)

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?

© Stack Overflow or respective owner

Related posts about python

Related posts about path