Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a line on Python

I'm trying to convert PHP code to Python, and I have problems with replacing lines. Although I find it easier to do using Python, I'm absolutely lost; I can find the line to replace, I can add something to the end of the line, but I can't write the line again on the file.

file = open("cache.ucb", 'rb')
for line in file:
   if line.split('~!')[0] == ex[4]:
       line += "~!" + mask[0]
       line = line.rstrip() + "\n"
       # Write on the file here!

Basically, the file uses ~! as a separator, and I read each line. If the first token separated with ~! of the line starts with ex[4], which could be for example Catbuntu, I want to append mask[0], which could be Bousie, on the end of that line. Then I remove the new line characters and add one to the end.

And there's the problem. I want to write the file as it was, but changing only that line. Is that possible?

like image 746
Addison Montgomery Avatar asked Mar 07 '26 07:03

Addison Montgomery


1 Answers

Assuming you're on python >=2.7, the following should work a treat

original = open(filename)
newfile = []
for line in original:
    if line.split('~!')[0] == ex[4]:
        line += "~!" + mask[0]
        line = line.rstrip() + "\n"
    newfile.append(line)
original.close()
amended.open(filename, "w")
amended.writeLines(newfile)
amended.close()

If for whatever reason you are on python 2.6 or lower, replace the second to last line with:

amended.write("".join(newfile))

EDIT: Fixed to replace a mistake copied from the question, factor out a filename.

like image 186
Drakekin Avatar answered Mar 09 '26 21:03

Drakekin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!