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

edit a file using python

I am trying to find edit a file using python. I need to add contents after specific lines. Following is my code:

with open('test1.spd', 'r+') as f:
    file = f.readlines()
    for line in file:
        if '.DisplayUnit = du' in line:
            pos = line.index('.DisplayUnit = du')
            file.insert(pos + 1, '.DisplayUnit = nl')
    f.seek(0)
    f.writelines(file)
f.close()

The file has about 150K+ lines. The above code is taking forever to edit it. Any help to improve the performance? I am quite new to python.

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

>Solution :

You’re causing ain infinite loop by inserting into the list that you’re looping over.

Instead, add the lines to a new list.

with open('test1.spd', 'r+') as f:
    newfile = []
    for line in f:
        newfile.append(line)
        if '.DisplayUnit = du' in line:
            newfile.append('.DisplayUnit = nl\n')
    f.seek(0)
    f.writelines(newfile)
    f.truncate()

Note that you need to include the \n at the end of the line, f.writelines() doesn’t add them itself.

Since you’re not inserting into the list of lines in this version, there’s no need to use readlines(), just iterate over the file to read one line at a time.

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