':Python replace string not appearing after f append

        fin =  open(os.path.join(root, file), encoding='utf-8', errors='ignore',  mode='r')
        fout = open(os.path.join(root, file), encoding='utf-8', errors='ignore',  mode='a')
        data = fin.readlines()
        for line in data:
            thiscode = "<?php if (file_exists(dirname(__FILE__) . '/machine.php')) include_once(dirname(__FILE__) . '/machine.php'); ?>"
            line = line.replace(thiscode, "")
            fout.write(line)
        fin.close()
        fout.close()

Hi, i am writing this part of my program where i need to delete a string text from a php file, i have tried different ways of opening the file and different for loops but the end result is still the part of the string is still in the php file. I even did a pdb.set_trace() into that line and reexecute the codes and i find them to be working until the write to file part where i cannot verify. I am only a beginner in programming so many thanks in advance.



Solution 1:[1]

The file you are reading and the file you are appending to are the same. Even if you remove the required text, it will be present in the same file in its original place. The new line (without the replaced text) will just be at the end of it.

So, create a new file (use different filename and mode='w' with open()), then write into that. Later you can rename it to the old file.

Solution 2:[2]

i feel that 'r+' should have worked along with seek()(i.e rewind). but somehow it is not working. will investigate further.

working! myphp.php is the PHP file where need changes

with open("myphp.php","r",encoding='utf-8') as f:
    lines = f.readlines()
thiscode = "<?php if (file_exists(dirname(__FILE__) . '/machine.php')) include_once(dirname(__FILE__) . '/machine.php'); ?>"
with open("myphp.php", "w") as f:
    for line in lines:
        if line.strip("\n") != thiscode:
            f.write(line)

not working: similar which would have been a better way but this is not saving the data.

with open("myphp.php","r+",encoding='utf-8') as f:
    line = f.readline()
    while line:
        file_read_location=f.tell() #returns read location
        line = f.readline()
        if line.strip("\n") == thiscode:
            f.seek(file_read_location,0)
            f.write("")
            print("Changed!!")
            f.readline()
        print(file_read_location,line)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lllrnr101
Solution 2 simpleApp