fileinput

naaman arphaksad at gmail.com
Fri Aug 14 05:41:41 CEST 2009


On Aug 13, 7:50 am, Dave Angel <da... at ieee.org> wrote:
> 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

here's the solution

import fileinput, sys

for line in fileinput.input(sys.argv[1],inplace=1):
    if (line[:-1]==r'drew'):
        line=line.replace(line,"fancy dog")
    sys.stdout.write(line)

I want to replace drew in my input file with fancy dog.
Tested with this input file
angel
heaven
flying monkees
lazy dogs
drew
blue sky
veritas

and got this
angel
heaven
flying monkees
lazy dogs
fancy dog
blue sky
veritas

So drew was replaced with fancy dog.
Thanks to your inputs I got this solved. :-))



More information about the Python-list mailing list