简体   繁体   中英

Replacing Values in a Text File

I am reading a text file.

One line from the text file looks like this and comes at the very end of the text file:

</DTS:Executable>

I am using replace("</DTS:Executable>","test from me")

Nothing gets replaced and the text stays as is.

What am I doing wrong?

What is the extension of the file ?

Can you try this sed command :

sed -i 's/original/new/g' file.txt

How about reading the data in list and replacing the last element, like so;

with open(fname) as f:
    content = f.readlines()
lines = [line.rstrip('\n') for line in file]
lines[-1] = "test from me"

Did this work?

If the file content are not to large then straight forward you can do something like this

with open(filename) as f:
    content = f.read()

content = content.replace("<old>", "<new>")

with open(filename, "w") as f:
    f.write(content)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM