Encephala
Encephala

Reputation: 348

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

Upvotes: 0

Views: 89

Answers (2)

Kasravnd
Kasravnd

Reputation: 107347

You can use tempfile.NamedTemporaryFile to create a temporary file object and write your lines in it the use shutil module to replace the temp file with your preceding file.

from tempfile import NamedTemporaryFile
import shutil

tempfile = NamedTemporaryFile(delete=False)
with open(file_name) as infile,tempfile:
    for line in infile:
        if 'characters' in line:
            tempfile.write('edited line')
        else:
            tempfile.write(line)

shutil.move(tempfile.name, file_name)

Upvotes: 0

jonrsharpe
jonrsharpe

Reputation: 122144

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).

Upvotes: 1

Related Questions