Home > front end >  Python - Read line from text file, update substring of line and write to new text file
Python - Read line from text file, update substring of line and write to new text file

Time:11-10

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

keyword | 0x01

Would like to know what's i did wrong here

CodePudding user response:

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.

  • Related