fileinput module doesn't work to spec?

Donn Cave donn at u.washington.edu
Tue Oct 24 12:43:15 EDT 2000


Quoth Dale Strickland-Clark <dale at out-think.NOSPAMco.uk>:
| According to the spec, the fileinput module should support overwriting
| of the input file after renaming it to preserve a backup. (Extract
| below.)
|
| It doesn't seem to work.
|
| 1. The input file is overwritten with an empty file.
| 2. No backup is taken
| 3. stdout is written to the console in stead of the input (now output)
| file
...
| # Tab delimited file to basic HTML Table converter
|
| import sys, fileinput
|
| def genCell(cell):
| 	if cell:
| 		if cell[0] == '"':
| 			cell = cell[1:-1]
| 		cell = cell.strip()
| 	if not cell:
| 		cell = ' '
| 	return ['<TD>',	cell, '</TD>']
|
| def genRow(line):
| 	row = ['<TR>']
| 	for cell in line.split('\t'):
| 		row = row + genCell(cell)
| 	row.append('</TR>\n')
| 	return row
|
| table = []
| for line in fileinput.input(sys.argv[1:], inplace = 1):
| 	table = table + genRow(line)
|
| 	
| print ''.join(table)

You're mainly missing the iterative aspect of this system.  It supports
multiple input files, and it sets up and tears down this redirection
all by itself.  After the last file, output goes back to stdout - it's
a feature.  If you want to write to the current input/output file, you
have to catch it while it's still current, not after all the input has
been read.  In your case, try

#   table = []
    for line in fileinput.input(sys.argv[1:], inplace = 1):
        hline = genRow(line)
        print string.join(hline, '')

There is a backup file, during the execution of that loop.  If you want
the backup file afterward, supply a third argument ("backup") with the
suffix string.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list