combining the path and fileinput modules

wo_shi_big_stomach wo_shi_big_stomach at mac.com
Wed Nov 22 23:30:40 EST 2006


Newbie to python writing a script to recurse a directory tree and delete
the first line of a file if it contains a given string. I get the same
error on a Mac running OS X 10.4.8 and FreeBSD 6.1.

Here's the script:

# start of program

# p.pl - fix broken SMTP headers in email files
#
# recurses from dir and searches all subdirs
# for each file, evaluates whether 1st line starts with "From "
# for each match, program deletes line

import fileinput
import os
import re
import string
import sys
from path import path

# recurse dirs
dir = path(/home/wsbs/Maildir)
for f in dir.walkfiles('*'):
 	#
	# test:
	# print f
	#
	# open file, search, change if necessary, write backup
 	for line in fileinput.input(f, inplace=1, backup='.bak'):
		# check first line only
		if fileinput.isfirstline():
 			if not re.search('^From ',line):
 				print line.rstrip('\n')
 		# just print all other lines
 		if not fileinput.isfirstline():
 			print line.rstrip('\n')
 	fileinput.close()
# end of program

The script produces this error:

Traceback (most recent call last):
  File "./p", line 22, in ?
    for line in fileinput.input(f, inplace=1, backup='.bak'):
  File "/sw/lib/python2.4/fileinput.py", line 231, in next
    line = self.readline()
  File "/sw/lib/python2.4/fileinput.py", line 300, in readline
    os.rename(self._filename, self._backupfilename)
OSError: [Errno 21] Is a directory

If I uncomment that test routine, and comment out the fileinput stuff,
the program DOES print the full pathname/filename for the variable f.

Many thanks for clues as to why fileinput.input doesn't like f.




More information about the Python-list mailing list