combining the path and fileinput modules

wo_shi_big_stomach wo_shi_big_stomach at mac.com
Sat Nov 25 04:14:58 CET 2006


Gabriel Genellina wrote:
> The filter should be applied to walkfiles. Something like this:
> 
> dir = path(/home/wsbs/Maildir)
> for f in filter(os.path.isfile, dir.walkfiles('*')):
>         #
>         # test:
>         # print f 

Thanks, this way f will print the full pathname/filename. But f already
does that using Jason Orendorff's path module:

dir = path('/home/wsbs/Maildir')
for f in dir.walkfiles('*'):
	print f

Printing the full path/filename isn't the problem. The problem instead
is how to supply f to fileinput.input().

Either the path or the os.path methods cause this line:

for line in fileinput.input(f, inplace=1, backup='.bak'):

to throw this error:

  File "./p2.py", line 23, in ?
    for line in fileinput.input(f, inplace=1, backup='.bak'):

At this point I believe the error has to do with fileinput, not the path
or os.path modules.

If I give fileinput.input() a hardcoded path/filename in place of 'f'
the program runs. However the program will not accept either f or 'f' as
an argument to fileinput.input().

Again, thanks for guidance on the care and feeding of fileinput.input()

/wsbs

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

# 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

# recurse dirs
dir = path('/home/wsbs/Maildir')
#for f in dir.walkfiles('*'):
for f in filter(os.path.isfile, dir.walkfiles('*')):
	#
	# test: this will print the full path/filename of each file
	print f
	#
	# open file, search, change if necessary, write backup
# 	for line in fileinput.input('f', inplace=1, backup='.bak'):
# 	# just print 2nd and subsequent lines
#   		if not fileinput.isfirstline():
# 			print line.rstrip('\n')
# 		# check first line only
# 		elif fileinput.isfirstline():
#  			if not re.search('^From ',line):
#  				print line.rstrip('\n')
# 	fileinput.close()





More information about the Python-list mailing list