Search code examples
pythonpython-3.xreadlines

Python edit line containing specific characters


I was wondering if there is a way to edit those lines of a file that contain certain characters. Something like this:

file.readlines()
for line in file:
    if 'characters' in line:
       file[line] = 'edited line'

If it matters: I'm using python 3.5


Solution

  • I think what you want is something like:

    lines = file.readlines()
    for index, line in enumerate(lines):
        if 'characters' in line:
            lines[index] = 'edited line'
    

    You can't edit the file directly, but you can write out the modified lines over the original (or, safer, write to a temporary file and renamed once you've validated it).