Programa de Python para reemplazar texto en un archivo

En este artículo, vamos a reemplazar Texto en un Archivo usando Python. Reemplazar texto podría ser borrar todo el contenido del archivo y reemplazarlo con texto nuevo o podría significar modificar solo palabras u oraciones específicas dentro del texto existente.

Método 1 : eliminar todo el texto y escribir texto nuevo en el mismo archivo

En este método reemplazamos todo el texto almacenado en el archivo de texto, para esto, abriremos el archivo en modo lectura y escritura y reescribirá todo el texto.

Python3

# Python program to replace text in a file
s = input("Enter text to replace the existing contents:")
f = open("file.txt", "r+")
 
# file.txt is an example here,
# it should be replaced with the file name
# r+ mode opens the file in read and write mode
f.truncate(0)
f.write(s)
f.close()
print("Text successfully replaced")

Producción: 

Enter text to replace the existing contents: Geeks
Text successfully replaced

Método 2 : usar la función Reemplazar en el ciclo for

El bucle for simple es una forma convencional de recorrer cada línea en el archivo de texto dado y encontrar la línea que queremos reemplazar. Luego, la línea deseada se puede reemplazar usando la función replace(). Finalmente, el archivo se abre en el modo de escritura y el contenido reemplazado se escribe en el archivo dado.

Python3

# Python program to replace text in a file
x = input("enter text to be replaced:")
y = input("enter text that will replace:")
 
# file.txt should be replaced with
# the actual text file name
f = open("file.txt", "r+")
 
# each sentence becomes an element in the list l
l = f.readlines()
 
# acts as a counter to know the
# index of the element to be replaced
c = 0
for i in l:
    if x in i:
 
        # Replacement carries the value
        # of the text to be replaced
        Replacement = i.replace(x, y)
 
        # changes are made in the list
        l = Replacement
    c += 1
 
# The pre existing text in the file is erased
f.truncate(0)
 
# the modified list is written into
# the file thereby replacing the old text
f.writelines(l)
f.close()
print("Text successfully replaced")

Producción:

Enter text to be replaced: Geeks
Enter text that will replace: Geekforgeeks
Text successfully replaced

Método 3 : usar el módulo del sistema operativo para reemplazar el archivo con texto nuevo

Usamos el módulo os para cambiar el nombre de un archivo nuevo con el nombre del archivo original. En este método, en lugar de editar el archivo ya existente, creamos un nuevo archivo con el contenido modificado y luego eliminamos el archivo antiguo y renombramos el nuevo archivo.

Python

# Program to replace text in a file
import os
x = input("Enter text that will replace the existing text:")
f = open("file.txt", "r+")
f1 = open("new.txt", "r+")
 
f1.write(x)
os.remove("file.txt")
os.rename("new.txt", "file.txt")
f1.close()
 
print("File replaced")

Producción:

Enter text that will replace the existing text: geeks
File replaced

Método 4: Usando fileinput.input()

El método fileinput.input() obtiene el archivo como entrada línea por línea y se utiliza principalmente para agregar y actualizar los datos en el archivo dado. El módulo fileinput y sys deben importarse al código Python actual para ejecutar el código sin errores. El siguiente código usa la función fileinput.input() para reemplazar el texto en una línea en Python.

Python3

import sys
import fileinput
 
x = input("Enter text to be replaced:")
y = input("Enter replacement text")
 
for l in fileinput.input(files = "file.txt"):
    l = l.replace(x, y)
    sys.stdout.write(l)

Producción:

Enter text to be replaced: Geeks
Enter replacement text: Geeksforgeeks

Publicación traducida automáticamente

Artículo escrito por prat0 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *