[Tutor] Example of modifying files in directory

Kent Johnson kent37 at tds.net
Wed May 28 20:50:57 CEST 2008


On Wed, May 28, 2008 at 9:50 AM, qsqgeekyogdty at tiscali.co.uk
<qsqgeekyogdty at tiscali.co.uk> wrote:
> Hello,
> I have been looking at using Beautifulsoup python module to make
> changes to some static html files a total of 167 files, but being a
> newb in programming was wondering first how to open, read/process the
> file, then write it, close it and then open the next file thus creating
> the loop.

I guess this is the simplest possible loop to do something to each
file in a directory. You would call processDir() with the path to the
directory to process. Define a function doSomethingWith() that takes
the file contents as an argument and returns the new file contents.

import os

def processDir(dirpath):
  for name in os.listdir(dirpath):
    filepath = os.path.join(dirpath, name)
    f = open(filepath)
    data = f.read()
    f.close()

    data = doSomethingTo(data)

    f = open(filepath, 'w')
    f.write(data)
    f.close()

This modifies files in place so you should have a backup. It assumes
everything in the dir is a file; if not you need to check in the loop.

HTH,
Kent


More information about the Tutor mailing list