17.12.2012 Views

Programmation PYTHON - Zenk - Security - Repository

Programmation PYTHON - Zenk - Security - Repository

Programmation PYTHON - Zenk - Security - Repository

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

358<br />

La bibliothèque standard<br />

TROISIÈME PARTIE<br />

Fichiers<br />

Exercice 5 : recherche et remplacement de texte<br />

Description<br />

L’objectif de cet exercice est de rechercher et remplacer un texte dans un fichier texte<br />

donné. Le texte à rechercher peut apparaître plusieurs fois dans le fichier et est fourni<br />

sous la forme d’une expression régulière.<br />

Points abordés<br />

Expressions régulières, lecture et écriture de fichiers, with.<br />

Solution<br />

Search and replace<br />

#!/usr/bin/python<br />

# -*- coding: utf8 -*import<br />

sys<br />

import os<br />

import re<br />

usage = """\<br />

Utilisation :<br />

%(prog)s <br />

Par exemple:<br />

%(prog)s pim.txt pam poum<br />

Remplacera toutes les occurences de "pam" en "poum"<br />

"""<br />

def sub_text(path, expr, repl):<br />

""" remplace un texte dans un fichier """<br />

# remplacement<br />

with open(path) as source:<br />

with open('%s.tmp' % path, 'w') as target:<br />

target.write(re.sub(expr, repl, source.read()))<br />

# renommage si tout s'est bien passé<br />

os.rename(path, '%s~' % path)<br />

os.rename('%s.tmp' % path, path)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!