[Tutor] overwriting input file

Kent Johnson kent37 at tds.net
Wed Feb 25 14:44:43 CET 2009


On Wed, Feb 25, 2009 at 8:26 AM, Noufal Ibrahim <noufal at nibrahim.net.in> wrote:
> Bala subramanian wrote:
>>
>> Hello all,
>>
>> query 1) How should i overwrite the input file
>> I want to open 5 files one by one, do some operation on the lines and
>> write the modified lines on the same file (overwritting). Can some please
>> tell me how to do it.
>
> import fileinput
> pat1=" R"
> pat2="U5"
> pat3="A3"
> files = fileinput.Fileinput(sys.argv[1:], inplace = 1)
> for i in files:
>  if pat1 in i: print i.replace(pat1," ")
>  if pat2 in i: print i.replace(pat2,"U ")
>  if pat3 in i: print i.replace(pat3,"A ")
> files.close()
>
> should work for you. Check out the fileinput documentation for details
> especially the 'inplace' argument. It's untested though.

This doesn't do quite the same as the original, it only writes
modified lines. Also I think it will add extra newlines, you should
use sys.stdout.write(i) instead of print i.

I would put the patterns in a list and use a loop. I think the test
for the pattern is not needed, the replace does the same search.
patterns = [
  (' R', ' '),
  ('U5', 'U '),
  ('A3', 'A ')
]

files = fileinput.Fileinput(sys.argv[1:], inplace = 1)
for line in files:
  for pat, repl in patterns:
    line = line.replace(pat, repl)
  sys.stdout.write(line)

Kent


More information about the Tutor mailing list