Advertisement
Rnery

Python - Fileinput

Mar 8th, 2022 (edited)
291
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.56 KB | Source Code | 1 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3.  
  4. from fileinput import FileInput
  5. from re import findall
  6.  
  7.  
  8. def replacement(file, regex, newphrase):
  9.     try:
  10.         with FileInput(file, inplace=True, backup='.bak') as file_founded:
  11.             for line in file_founded:
  12.                 if findall(regex, line):
  13.                     print(newphrase, end='\n')
  14.                 else:
  15.                     print(line, end='')
  16.     except FileNotFoundError as err:
  17.         print(err)
  18.  
  19.  
  20. if __name__ == '__main__':
  21.     replacement('testadeiro.txt', '^homem', 'mulher')
  22.  
Tags: python python3
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement