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

How to delete a string from all files in a directory

I want all files in directory "path" to have the string "error" removed from them and the result to be saved in the same file that was editted. My current code (below) ends up clearing up the entire file, rather than just removing the string and keeping everything else the same.

import os


path = "path"
files = os.listdir(path)
error = "string"


for index, file in enumerate(files):
    with open(os.path.join(path, file)) as fin, open(os.path.join(path, file), "w+") as fout:
        for line in fin:
            line = line.replace(error, "f")
            fout.write(line)

>Solution :

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

import os

path = "path"
files = os.listdir(path)
error = "string"

for index, file in enumerate(files):
    with open(os.path.join(path, file), 'r') as fin:
       d = din.read()
    with open(os.path.join(path, file), "w") as fout:
        d = d.replace(error, "")
        fout.write(d)
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