Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – Read line from text file, update substring of line and write to new text file

I have a function to read a text file, search line by line, if the line contains keyword, compare its value and update the value
However, when I trying to writelines to new text file, the changes is not taken, here’s my code:

with open(oldfile, 'r') as file :
    filedata = file.readlines()

for line in filedata:
    if "keyword" in line:
        value = line.strip().split(' | ')[-1]
        print(value)
        if value != '0x00':
            print('replacing value')
            line = line.replace(value, '0x00')
            print(line)

with open(newfile, 'w') as file:
    file.writelines(filedata)

Example of old text file:

keyword | 0x01
random | 0x01
random2 | 0x01

New text file still containing

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

keyword | 0x01

Would like to know what’s i did wrong here

>Solution :

with open("text", 'r') as file :
    filedata = file.readlines()
newlines = []
for line in filedata:
    if "keyword" in line:
        value = line.strip().split(' | ')[-1]
        print(value)
        if value != '0x00':
            print('replacing value')
            line = line.replace(value, '0x00')
            print(line)
        newlines.append(line)

with open("text2", 'w') as file:
    file.writelines("\n".join(newlines))

python treats line as a string, not a pointer to a string.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading