combining the path and fileinput modules

wo_shi_big_stomach wo_shi_big_stomach at
Sat Nov 25 16:58:26 CET 2006

Gabriel Genellina wrote:
> At Saturday 25/11/2006 00:14, wo_shi_big_stomach 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
> The filter is used to exclude directories. fileinput can't handle
> directories.


Both routines above produce identical output -- full path/filenames.
Neither prints just a directory name.

>> 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().
> Tried with (f,) ?
> Notice that *this* error is not the same as your previous error.

  File "", line 23, in ?
    for line in fileinput.input(f,):
line 231, in next
    line = self.readline()
line 320, in readline
    self._file = open(self._filename, "r")

This looks similar to before -- fileinput.input() still isn't operating
on the input.

Again, I'm looking 1) walk through all files in a directory tree and 2)
using fileinput, evaluate and possibly edit the files.

The current version of the program is below.



# start of program
import fileinput
import os
import re
import string
import sys
from path import path

# - 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,):
	# just print 2nd and subsequent lines
  		if not fileinput.isfirstline():
			print line.rstrip('\n')
		# check first line only
		elif fileinput.isfirstline():
 			if not'^From ',line):
 				print line.rstrip('\n')

# end of program

More information about the Python-list mailing list