user1973591
user1973591

Reputation:

How to write into a file at a particular Match

I have one file at the location "C:\Temp" the file name is arun.txt. The content of the file is like following

test=
pqr=
lmn=

I want to find the line with 'pqr=' and modfiy this as 'pwr=xyz'

I am not much expert in python.

But following code I have written but its neither doing anything nor returning any error.

f = open('C:\Temp\arun.txt', 'r+')
        for line in f.readline():
                if line == "pqr=":
                        f.write('pqr=xyz')

Can anyone please suggest me if I am doing something wrong here.

Upvotes: 0

Views: 29

Answers (2)

user1907906
user1907906

Reputation:

with open("input.txt") as input, open("output.txt", "w") as output:
    for line in input:
        if line.startswith("pqr="):
            output.write("pqr=xyz\n")
        else:
            output.write(line)

Upvotes: 1

jamylak
jamylak

Reputation: 133564

fileinput.input with argument inplace=True has your print statements redirected to a temporary file which is renamed to your original file to allow inplace editing.

for line in fileinput.input('Temp', inplace=True):
    line = line.rstrip('\n')
    if line == 'pqr=':
        print line + 'xyz'
    else:
        print line

The temporary file is by default, the original file name + '.bak'. This makes the program process safe, as opposed to just using out.txt as a file name since you may decide to run this program on another file, which may overwrite out.txt as you are writing to it. Another safe approach would be to rename a tempfile.NamedTemporaryFile

Upvotes: 1

Related Questions