JPablos

Buscar-Reemplazar texto. Python

Mar 25th, 2021 (edited)
686
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.14 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. # -*- coding: utf-8 -*-
  4.  
  5. """
  6. Creado con Spyder
  7.  
  8. Busca/Reemplaza texto o patrón en un archivo de texto.
  9. """
  10.  
  11.  
  12. from pathlib import Path
  13.  
  14.  
  15. def busca_reemplaza(archivo: str, busca: str, reemplaza: str):
  16.     """
  17.    Parameters.
  18.    ----------
  19.    archivo: "Nombre/del/archivo/archivo.txt"
  20.  
  21.        Cualquier archivo tipo texto.
  22.  
  23.    busca: str
  24.    
  25.        Texto o patrón a buscar.
  26.  
  27.        Sí la palabra a buscar/reemplazar contiene apostrofe,
  28.        usar entrecomillado doble.
  29.        Ejemplo de uso:
  30.            busca_reemplaza("archivo.txt", "you'll", "you will")
  31.  
  32.    reemplaza : str
  33.  
  34.        Texto o patrón a buscar.
  35.        El archivo a modificar debe estar en mismo directorio donde se ejecute
  36.        la función. Si no, reporta:
  37.  
  38.        FileNotFoundError: [Errno 2] No such file or directory: 'archivo.txt'.
  39.  
  40.    Returns
  41.    -------
  42.    None.
  43.  
  44.    """
  45.     path = Path(archivo)
  46.     text = path.read_text(encoding='utf-8')
  47.     text = text.replace(busca, reemplaza)
  48.     path.write_text(text, encoding='utf-8')
  49.  
  50. # busca_reemplaza("archivo.txt", "you'll", "you will")    <-- Ejemplo de uso
  51.  
  52.  
Add Comment
Please, Sign In to add comment