[Tutor] [File Input Module]Replacing string in a file

vanam raghavendra.gv.vanam at gmail.com
Thu Jan 28 18:19:48 CET 2010


Hi all,

As it was suggested before in the mailing list about the query
regarding replacing string in the file, i have used the module File
input for replacing the string in the file.

For understanding and execution purpose, i have just included Python
as a string in the file and want it to be replaced to PYTHON.

Below are my queries and code: (Correct me if my understanding is wrong???????)

1))

import fileinput
x = fileinput.input('data.txt',inplace=0)
for line in x:
     line = line.replace('Python','PYTHON)
     print line,
x.close()

The above piece of code will not create any backup file but  it will
replace PYTHON (Print on the console) but not physically write to the
file.

2)))

import fileinput
x = fileinput.input('data.txt',inplace=1)
for line in x:
    line = line.replace('Python','PYTHON')
    print line,
x.close()

The above piece of code will create backup file but hidden (in the
form of bak file) and it will physically write to the file -- I have
verified the contents of data.txt after the file operation and it had
written successfully.But why it is not printing line i.e. string in
the file on the console.

3)))

import fileinput
x = fileinput.input('data.txt',inplace=1)
for line in x:
    line = line.replace('Python','PYTHON')
x.close()

The above piece of code after execution is wiping out the full
contents. But addition of print line, is exactly replacing the string,
what exactly addition of print is making difference???

4)))

import fileinput
x = fileinput.input('data.txt',inplace=1,backup='content.txt')
for line in x:
    line = line.replace('Python','PYTHON')
    print line,
x.close()

The above piece is creating a backup file by name data.txtcontent.txt
(I am not sure whether created file name is correct or not?) and to
the back up file it had added previous content i.e., Python and it had
replaced the contents in data.txt to PYTHON

5)))

Suppose if data.txt has string Python written in Font size 72 and when
i display the string on the console ie. by below piece of code

import fileinput
x = fileinput.input('data.txt',inplace=0)
for line in x:
      print line,
x.close()

It wouldnt print with the same Font size on the console (This wont
prove anything wrong as the same font could be backed with a different
file name)

Do let me know if my understanding is correct.
-- 
Raghavendra  Vanam


More information about the Tutor mailing list