Python: edición en el lugar usando FileInput

Python3 fileinputproporciona muchas funciones útiles que se pueden usar para hacer muchas cosas sin mucho código. Es útil en muchos lugares, pero en este artículo, usaremos la entrada de archivo para realizar la edición en el lugar en un archivo de texto. Básicamente, cambiaremos el texto en un archivo de texto sin crear ningún otro archivo ni sobrecarga.

Sintaxis:

FileInput(filename, inplace=True, backup='.bak')

Nota: La copia de seguridad es una extensión del archivo de copia de seguridad creado antes de la edición.

Ejemplo 1: cambiar solo la primera línea del archivo

Archivo de texto:

fileinput-python-1

# Python code to change only first line of file
import fileinput
  
filename = "GFG.txt"
  
with fileinput.FileInput(filename, 
                         inplace = True, backup ='.bak') as f:
  
    for line in f:
        if f.isfirstline():
            print("changing only first line", end ='\n')
        else:
            print(line, end ='')

Producción:

fileinput-python-2

Ejemplo 2: busque y reemplace la línea con otra línea en el archivo

Archivo de texto:

fileinput-python-3

# python3 code to search and 
# replace line with other line in file
import fileinput
  
filename = "GFG.txt"
  
with fileinput.FileInput(filename,
                         inplace = True, backup ='.bak') as f:
      
    for line in f:
        if "search this line and change it\n" == line:
            print("changing the matched line with this line",
                  end ='\n')
        else:
            print(line, end ='')

Producción:

fileinput-python-4

Ejemplo 3: busque texto en línea y reemplace esa línea con otra línea en el archivo.

Archivo de texto:

fileinput-python

# python3 code to search text in 
# line and replace that line with 
# other line in file
import fileinput
  
filename = "GFG.txt"
  
with fileinput.FileInput(filename,
                         inplace = True, backup ='.bak') as f:
    for line in f:
        if "searchtext" in line:
            print("changing this line with line that contains searched text",
                  end ='\n')
        else:
            print(line, end ='')

Producción:

fileinput-python-6

Ejemplo 4: Buscar texto y reemplazar ese texto en el archivo.

Archivo de texto:

fileinput-python1

# python code to search
# text and replace that text
# in file
  
import fileinput
  
filename = "GFG.txt"
  
with fileinput.FileInput(filename, 
                         inplace = True, backup ='.bak') as f:
      
    for line in f:
        if "replace text" in line:
            print(line.replace("replace text",
                               "changed text"), end ='')
        else:
            print(line, end ='')

Producción:

fileinput-python-7

Publicación traducida automáticamente

Artículo escrito por siddhantkumarupmanyu 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 *