[File Input Module]Replacing string in a file

vanam raghavendra.gv.vanam at gmail.com
Fri Jan 29 06:36:27 CET 2010


Hi all,

For 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



More information about the Python-list mailing list