Hola, la línea a editar o modificar tendrá que ser elegida en base a algún criterio, por ejemplo contener algo que deba ser reemplazado (quizás la línea entera podría reemplazarse).
Hay distintas alternativas para hacer esto:
Escribir el contenido en un nuevo fichero y reemplazar el viejo fichero con el nuevo:
from tempfile import mkstemp
from shutil import move
from os import remove, close
def replace(file_path, pattern, subst):
#Create temp file
fh, abs_path = mkstemp()
with open(abs_path,'w') as new_file:
with open(file_path) as old_file:
for line in old_file:
new_file.write(line.replace(pattern, subst))
close(fh)
#Remove original file
remove(file_path)
#Move new file
move(abs_path, file_path)
Añadir contenido a líneas en el fichero que se quiere editar (en este ejemplo se añade el número de línea):
import fileinput
for line in fileinput.input("test.txt", inplace=True):
print "%d: %s" % (fileinput.filelineno(), line),
Reemplazar un patrón en el fichero usando expresiones regulares, se usaría como por ejemplo replaceAll("/ejemplo.txt","Hola\sMundo!$","Adios\sMundo."):
import fileinput
import sys
def replaceAll(file,searchExp,replaceExp):
for line in fileinput.input(file, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
sys.stdout.write(line)
Reemplazo:
import fileinput
# Does a list of files, and
# redirects STDOUT to the file in question
for line in fileinput.input(files, inplace = 1):
print line.replace("foo", "bar"),
Reemplazo masivo:
import re
def replace(file, pattern, subst):
# Read contents from file as a single string
file_handle = open(file, 'r')
file_string = file_handle.read()
file_handle.close()
# Use RE package to allow for replacement (also allowing for (multiline) REGEX)
file_string = (re.sub(pattern, subst, file_string))
# Write contents to file.
# Using mode 'w' truncates the file.
file_handle = open(file, 'w')
file_handle.write(file_string)
file_handle.close()
Saludos