fileinput

Dave Angel davea at ieee.org
Thu Aug 13 07:50:30 EDT 2009


naaman wrote:
> On Aug 12, 1:35 pm, Dave Angel <da... at ieee.org> wrote:
>   
>> naaman wrote:
>>     
>>> I'm writing my first Python script and
>>> I want to use fileinput to open a file in r+ mode.
>>> Tried fileinput.input(sys.argv[1:],"r+") but that didn't work.
>>> ANy ideas?
>>>       
>>> Need to find and overwrite a line in a file several times.
>>> I can do it using open and seek() etc. but was wondering if I can use
>>> fileinput.
>>>       
>>> thanks;
>>>       
>> I haven't used it, but check out the 'inplace' keyword parameter.
>>
>> DaveA
>>     
>
> I've only Python for a week so I'm not sure what inplace does
>
>   
You should read the docs for it
    ( http://www.python.org/doc/2.6.2/library/fileinput.html  ),
but it's not very clear to me either  So I dug up an example on the web:
     (ref:   http://effbot.org/librarybook/fileinput.htm )

import fileinput, sys

for line in fileinput.input(inplace=1):
    # /convert Windows/DOS text files to Unix files/
    if line[-2:] == "\r\n":
        line = line[:-2] + "\n"
    sys.stdout.write(line)


The inplace argument tells it to create a new file with the same name as 
the original (doing all the necessary nonsense with using a scratch 
file, and renaming/deleting) for each file processed.  Stdout is pointed 
to that new version of the file.  Notice that you have to explicitly 
write everything you want to wind up in the file -- if a given line is 
to remain unchanged, you just write "line" directly.

If you're new to Python, I do not recommend trying to do open/seek to 
update a text file in place, especially if you're in DOS.  There are 
lots of traps.  the inplace method of fileinput avoids these by 
implicitly creating temp files and handling the details for you, which 
probably works great if you're dealing with text, in order.

DaveA




More information about the Python-list mailing list