Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Replace function to edit files

I have a results.txt file which looks like this:

[["12 - 22 - 30 - 31 - 34 - 39 - 36"],
["13 - 21 - 28 - 37 - 39 - 45 - 6"],
["2 - 22 - 32 - 33 - 37 - 45 - 11"],
["3 - 5 - 11 - 16 - 41 - 48 - 32"],
["2 - 3 - 14 - 29 - 35 - 42 12"],
["14 - 30 - 31 - 36 - 44 - 47 26"]]

I want to replace the " - " in the results.txt file with '","' so it looks for like a python list.

I try to used the code below, but the output looks exactly like the results.txt

output = open("results2.txt", 'w')
f = open("results.txt", 'r')
read = f.readlines()

for i in read:
    i.replace(" - ",'","')
    output.write(i)
like image 603
Harpal Avatar asked Jan 24 '26 00:01

Harpal


2 Answers

for i in read:
    # the string.replace() function don't do the change at place
    # it's return a new string with the new changes.
    a = i.replace(" - ",",")  
    output.write(a)
like image 68
mouad Avatar answered Jan 26 '26 18:01

mouad


String methods return a new string. Write that out instead.

output.write(i.replace(" - ",","))
like image 41
Ignacio Vazquez-Abrams Avatar answered Jan 26 '26 18:01

Ignacio Vazquez-Abrams



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!