In [2]:
from __future__ import print_function

Fichiers et entrées/sorties

Pour écrire ou lire dans un fichier, open() renvoie un objet de type fichier, et est utilisée plus généralement avec deux arguments : open(nomfichier, mode).


In [11]:
f=open('fichiertravail.txt', 'w')

Le premier argument est une chaîne de caractères contenant le nom du fichier. Le deuxième argument est une autre chaîne de caractères contenant quelques caractères décrivant la manière d’utiliser le fichier. mode vaut 'r' quand le fichier doit être seulement lu, 'w' pour seulement être écrit (un fichier déjà existant avec le même nom sera effacé), et 'a' ouvre le fichier en ajout ; les données écrites dans le fichier seront automatiquement ajoutées à la fin. 'r+' ouvre le fichier pour la lecture et l’écriture. L’argument mode est facultatif ; 'r' sera pris par défaut s’il est omis.

Pour écrire dans un fichier, on peut utiliser la primitive f.write( chaine ), qui écrit la chaîne de caractères dans le fichier


In [12]:
f.write('Voici un test\n')

Pour écrire quelque chose d’autre qu’une chaîne il est nécessaire de commencer par le convertir en chaîne :


In [13]:
value = ('la reponse est', 42)
s = str(value)
f.write(s)

Une fois le fichier utilisé, il faut le fermer avec f.close(). Après avoir appelé f.close(), les tentatives d’utiliser l’objet fichier échoueront automatiquement.


In [14]:
f.close()

Il existe une façon plus adéquate pour travailler sur un fichier, qui permet de ne pas avoir besoin d'utiliser close. Nous verrons cette syntaxe en utilisant f.read( taille ) qui lit une certaine quantité de données et les retourne en tant que chaîne de caractères. taille est un argument numérique facultatif. Quand taille est omis ou négatif, le contenu entier du fichier sera lu et retourné. Autrement, au plus taille octets sont lus et retournés.


In [15]:
with open('fichiertravail.txt', 'r') as f:
    s = f.read()
    print (s)


Voici un test
('la reponse est', 42)

f.readline() lit une seule ligne à partir du fichier ; un caractère de fin de ligne (\n) est laissé à l’extrémité de la chaîne de caractères lue, et est seulement omis sur la dernière ligne du fichier si le fichier ne se termine pas par une fin de ligne. Cela rend la valeur de retour non ambiguë ; si f.readline() renvoie une chaîne de caractères vide, la fin du fichier a été atteinte, alors qu’une fin de ligne est représentée par '\n', une chaîne de caractères contenant seulement une seule fin de ligne.


In [25]:
with open('fichiertravail.txt', 'r') as f:
    s = f.readline()
    while s != '':
        print (s)
        s = f.readline()


Voici un test

('la reponse est', 42)

f.readlines() renvoie une liste contenant toutes les lignes de données dans le fichier. Si un paramètre optionnel sizehint est donné, alors elle lit le nombre d’octets indiqué, plus autant d’octets qu’il en faut pour compléter la dernière ligne commencée, et renvoie la liste des lignes ainsi lues. Cela est souvent utile pour per- mettre la lecture par lignes efficace, sans devoir charger entièrement le fichier en mémoire. La liste retournée est entièrement faite de lignes complètes.


In [26]:
with open('fichiertravail.txt', 'r') as f:
    lines = f.readlines()
for i, l in enumerate(lines):
    print ('ligne', i, ':', l)


ligne 0 : Voici un test

ligne 1 : ('la reponse est', 42)

Le module pickle

Les chaînes de caractères peuvent facilement être écrites et lues dans un fichier. Les nombres demandent un peu plus d’effort, puisque la méthode read() renvoie seulement les chaînes de caractères, qui devront être passées vers une fonction comme int(), qui prend une chaîne de caractères comme '123' et renvoie sa valeur numérique 123. Cependant, quand vous voulez sauvegarder des types de données plus complexes comme des listes, des dictionnaires, ou des instances de classe, les choses deviennent beaucoup plus compliquées.

Plutôt que faire écrire et déboguer constamment par les utilisateurs le code pour sauvegarder des types de données complexes, Python fournit un module standard appelé pickle. C’est un module étonnant qui peut prendre presque n’importe quel objet Python (même quelques formes de code Python !), et le convertir en une représentation sous forme de chaîne de caractères ; ce processus s’appelle pickling. Reconstruire l’objet à partir de sa représentation en chaîne de caractères s’appelle unpickling. Entre pickling et unpickling, la chaîne de caractères représentant l’objet a pu avoir été enregistrée dans un fichier ou des données, ou avoir été envoyée à une machine éloignée via une connexion réseau.

Si vous avez un objet x, et un objet fichier f ouvert en écriture, la voie la plus simple de pickler l’objet prend seulement une ligne de code :

pickle.dump(x, f)

Pour unpickler l’objet, si f est un objet fichier ouvert en lecture :

x = pickle.load(f)

La gestion des fichiers

Il est possible de manipuler les primitives systèmes en Python. La plupart des fonctions du système sont disponible dans le module os:


In [27]:
import os

Pour connaître toutes les fonctions disponibles, il est possible d'utiliser help(os) ou dir(os).

Pour les tâches courantes de gestion de fichiers et répertoires, la module shutil fournit une interface de haut niveau facile à utiliser :


In [29]:
import shutil
shutil.copyfile('fichiertravail.txt', 'macopie.txt')
shutil.move('macopie.txt', 'lacopie.txt')

Le module glob fournit une fonction pour construire des listes de fichiers à partir de recherches avec jockers (les *) dans des répertoires :


In [36]:
import glob
glob.glob('*.txt')


Out[36]:
['fichiertravail.txt', 'lacopie.txt']

Accès à internet

Il y a un certain nombre de modules pour accéder à Internet et pour traiter les protocoles de l’Internet. Deux des plus simples sont urllib2 pour récupérer des données depuis des url et smtplib pour envoyer du courrier :


In [39]:
import urllib2
for line in urllib2.urlopen('http://www.python.org'):
    if 'meta' in line: # on affiche uniquement les lignes contenant la balise meta
        print (line)


    <meta charset="utf-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="application-name" content="Python.org">

    <meta name="msapplication-tooltip" content="The official home of the Python Programming Language">

    <meta name="apple-mobile-web-app-title" content="Python.org">

    <meta name="apple-mobile-web-app-capable" content="yes">

    <meta name="apple-mobile-web-app-status-bar-style" content="black">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta name="HandheldFriendly" content="True">

    <meta name="format-detection" content="telephone=no">

    <meta http-equiv="cleartype" content="on">

    <meta http-equiv="imagetoolbar" content="false">

    <meta name="msapplication-TileImage" content="/static/metro-icon-144x144-precomposed.png"><!-- white shape -->

    <meta name="msapplication-TileColor" content="#3673a5"><!-- python blue -->

    <meta name="msapplication-navbutton-color" content="#3673a5">

    <meta property="og:site_name" content="Python.org">

    <meta property="og:type" content="website">

    <meta property="og:title" content="Welcome to Python.org">

    <meta name="description" content="The official home of the Python Programming Language">

    <meta name="og:description" content="The official home of the Python Programming Language">

    <meta name="keywords" content="Python programming language object oriented web free open source software license documentation download community">

    <meta property="og:tag" content="Python programming language object oriented web free open source software license documentation download community">

    <meta property="og:published_time" content="">

    <meta property="og:modified_time" content="">

    <meta property="og:author" content="">

    <meta property="og:section" content=""> 

    <meta property="og:url" content="">

    <meta property="og:image" content="">

    <meta property="og:video" content="">

            <nav class="meta-navigation container" role="navigation">

    <li class="python-meta current_item selectedcurrent_branch selected">

    <li class="psf-meta ">

    <li class="docs-meta ">

    <li class="pypi-meta ">

    <li class="jobs-meta ">

    <li class="shop-meta ">

Un exemple pour smtplib :

import smtplib

server = smtplib.SMTP('localhost')

server.sendmail('expediteur@a.com', 'destinataire@b.org',

"""To: destinataire

From: me

Un message de test

""")

server.close()

Les autres modules

Les autres modules sont décrits ici : https://docs.python.org/2/library/

  1. Gestion des chaînes de caractères

    • string — Opérations communes sur les chaînes de caractères
    • re — Expressions régulières
    • struct — Interprèter les chaînes de caractères comme des paquets de données binaires
    • difflib — Aides pour calculer des différences
    • StringIO — Lecture et écriture des chaînes comme des fichiers
    • cStringIO — Versin plus rapide de StringIO
    • textwrap — Wrapping et remplissage de texte
    • codecs — Registres des codecs et classes de base
    • unicodedata — Base de données Unicode
    • stringprep — Préparation pour la conversion en chaînes internet
    • fpformat — Conversions en virgules floattante
  2. Types de données

    • datetime — Basic date and time types
    • calendar — General calendar-related functions
    • collections — High-performance container datatypes
    • heapq — Heap queue algorithm
    • bisect — Array bisection algorithm
    • array — Efficient arrays of numeric values
    • sets — Unordered collections of unique elements
    • sched — Event scheduler
    • mutex — Mutual exclusion support
    • Queue — A synchronized queue class
    • weakref — Weak references
    • UserDict — Class wrapper for dictionary objects
    • UserList — Class wrapper for list objects
    • UserString — Class wrapper for string objects
    • types — Names for built-in types
    • new — Creation of runtime internal objects
    • copy — Shallow and deep copy operations
    • pprint — Data pretty printer
    • repr — Alternate repr() implementation
  3. Numeric and Mathematical Modules

    • numbers — Numeric abstract base classes
    • math — Mathematical functions
    • cmath — Mathematical functions for complex numbers
    • decimal — Decimal fixed point and floating point arithmetic
    • fractions — Rational numbers
    • random — Generate pseudo-random numbers
    • itertools — Functions creating iterators for efficient looping
    • functools — Higher-order functions and operations on callable objects
    • operator — Standard operators as functions
  4. File and Directory Access

    • os.path — Common pathname manipulations
    • fileinput — Iterate over lines from multiple input streams
    • stat — Interpreting stat() results
    • statvfs — Constants used with os.statvfs()
    • filecmp — File and Directory Comparisons
    • tempfile — Generate temporary files and directories
    • glob — Unix style pathname pattern expansion
    • fnmatch — Unix filename pattern matching
    • linecache — Random access to text lines
    • shutil — High-level file operations
    • dircache — Cached directory listings
    • macpath — Mac OS 9 path manipulation functions
  5. Data Persistence

    • pickle — Python object serialization
    • cPickle — A faster pickle
    • copy_reg — Register pickle support functions
    • shelve — Python object persistence
    • marshal — Internal Python object serialization
    • anydbm — Generic access to DBM-style databases
    • whichdb — Guess which DBM module created a database
    • dbm — Simple “database” interface
    • gdbm — GNU’s reinterpretation of dbm
    • dbhash — DBM-style interface to the BSD database library
    • bsddb — Interface to Berkeley DB library
    • dumbdbm — Portable DBM implementation
    • sqlite3 — DB-API 2.0 interface for SQLite databases
  6. Data Compression and Archiving

    • zlib — Compression compatible with gzip
    • gzip — Support for gzip files
    • bz2 — Compression compatible with bzip2
    • zipfile — Work with ZIP archives
    • tarfile — Read and write tar archive files
  7. File Formats

    • csv — CSV File Reading and Writing
    • ConfigParser — Configuration file parser
    • robotparser — Parser for robots.txt
    • netrc — netrc file processing
    • xdrlib — Encode and decode XDR data
    • plistlib — Generate and parse Mac OS X .plist files
  8. Cryptographic Services

    • hashlib — Secure hashes and message digests
    • hmac — Keyed-Hashing for Message Authentication
    • md5 — MD5 message digest algorithm
    • sha — SHA-1 message digest algorithm
  9. Generic Operating System Services

    • os — Miscellaneous operating system interfaces
    • io — Core tools for working with streams
    • time — Time access and conversions
    • argparse — Parser for command-line options, arguments and sub-commands
    • optparse — Parser for command line options
    • getopt — C-style parser for command line options
    • logging — Logging facility for Python
    • logging.config — Logging configuration
    • logging.handlers — Logging handlers
    • getpass — Portable password input
    • curses — Terminal handling for character-cell displays
    • curses.textpad — Text input widget for curses programs
    • curses.ascii — Utilities for ASCII characters
    • curses.panel — A panel stack extension for curses
    • platform — Access to underlying platform’s identifying data
    • errno — Standard errno system symbols
    • ctypes — A foreign function library for Python
  10. Optional Operating System Services

    • select — Waiting for I/O completion
    • threading — Higher-level threading interface
    • thread — Multiple threads of control
    • dummy_threading — Drop-in replacement for the threading module
    • dummy_thread — Drop-in replacement for the thread module
    • multiprocessing — Process-based “threading” interface
    • mmap — Memory-mapped file support
    • readline — GNU readline interface
    • rlcompleter — Completion function for GNU readline
  11. Interprocess Communication and Networking

    • subprocess — Subprocess management
    • socket — Low-level networking interface
    • ssl — TLS/SSL wrapper for socket objects
    • signal — Set handlers for asynchronous events
    • popen2 — Subprocesses with accessible I/O streams
    • asyncore — Asynchronous socket handler
    • asynchat — Asynchronous socket command/response handler
  12. Internet Data Handling

    • email — An email and MIME handling package
    • json — JSON encoder and decoder
    • mailcap — Mailcap file handling
    • mailbox — Manipulate mailboxes in various formats
    • mhlib — Access to MH mailboxes
    • mimetools — Tools for parsing MIME messages
    • mimetypes — Map filenames to MIME types
    • MimeWriter — Generic MIME file writer
    • mimify — MIME processing of mail messages
    • multifile — Support for files containing distinct parts
    • rfc822 — Parse RFC 2822 mail headers
    • base64 — RFC 3548: Base16, Base32, Base64 Data Encodings
    • binhex — Encode and decode binhex4 files
    • binascii — Convert between binary and ASCII
    • quopri — Encode and decode MIME quoted-printable data
    • uu — Encode and decode uuencode files
  13. Structured Markup Processing Tools

    • HTMLParser — Simple HTML and XHTML parser
    • sgmllib — Simple SGML parser
    • htmllib — A parser for HTML documents
    • htmlentitydefs — Definitions of HTML general entities
    • XML Processing Modules
    • XML vulnerabilities
    • xml.etree.ElementTree — The ElementTree XML API
    • xml.dom — The Document Object Model API
    • xml.dom.minidom — Minimal DOM implementation
    • xml.dom.pulldom — Support for building partial DOM trees
    • xml.sax — Support for SAX2 parsers
    • xml.sax.handler — Base classes for SAX handlers
    • xml.sax.saxutils — SAX Utilities
    • xml.sax.xmlreader — Interface for XML parsers
    • xml.parsers.expat — Fast XML parsing using Expat
  14. Internet Protocols and Support

    • webbrowser — Convenient Web-browser controller
    • cgi — Common Gateway Interface support
    • cgitb — Traceback manager for CGI scripts
    • wsgiref — WSGI Utilities and Reference Implementation
    • urllib — Open arbitrary resources by URL
    • urllib2 — extensible library for opening URLs
    • httplib — HTTP protocol client
    • ftplib — FTP protocol client
    • poplib — POP3 protocol client
    • imaplib — IMAP4 protocol client
    • nntplib — NNTP protocol client
    • smtplib — SMTP protocol client
    • smtpd — SMTP Server
    • telnetlib — Telnet client
    • uuid — UUID objects according to RFC 4122
    • urlparse — Parse URLs into components
    • SocketServer — A framework for network servers
    • BaseHTTPServer — Basic HTTP server
    • SimpleHTTPServer — Simple HTTP request handler
    • CGIHTTPServer — CGI-capable HTTP request handler
    • cookielib — Cookie handling for HTTP clients
    • Cookie — HTTP state management
    • xmlrpclib — XML-RPC client access
    • SimpleXMLRPCServer — Basic XML-RPC server
    • DocXMLRPCServer — Self-documenting XML-RPC server
  15. Multimedia Services

    • audioop — Manipulate raw audio data
    • imageop — Manipulate raw image data
    • aifc — Read and write AIFF and AIFC files
    • sunau — Read and write Sun AU files
    • wave — Read and write WAV files
    • chunk — Read IFF chunked data
    • colorsys — Conversions between color systems
    • imghdr — Determine the type of an image
    • sndhdr — Determine type of sound file
    • ossaudiodev — Access to OSS-compatible audio devices
  16. Internationalization

    • gettext — Multilingual internationalization services
    • locale — Internationalization services
  17. Program Frameworks

    • cmd — Support for line-oriented command interpreters
    • shlex — Simple lexical analysis
  18. Graphical User Interfaces with Tk

    • Tkinter — Python interface to Tcl/Tk
    • ttk — Tk themed widgets
    • Tix — Extension widgets for Tk
    • ScrolledText — Scrolled Text Widget
    • turtle — Turtle graphics for Tk
    • IDLE
    • Other Graphical User Interface Packages
  19. Development Tools

    • pydoc — Documentation generator and online help system
    • doctest — Test interactive Python examples
    • unittest — Unit testing framework
    • 2to3 - Automated Python 2 to 3 code translation
    • test — Regression tests package for Python
    • test.test_support — Utility functions for tests
  20. Debugging and Profiling

    • bdb — Debugger framework
    • pdb — The Python Debugger
    • Debugger Commands
    • The Python Profilers
    • hotshot — High performance logging profiler
    • timeit — Measure execution time of small code snippets
    • trace — Trace or track Python statement execution
  21. Python Runtime Services

    • sys — System-specific parameters and functions
    • sysconfig — Provide access to Python’s configuration information
    • __builtin__ — Built-in objects
    • future_builtins — Python 3 builtins
    • __main__ — Top-level script environment
    • warnings — Warning control
    • contextlib — Utilities for with-statement contexts
    • abc — Abstract Base Classes
    • atexit — Exit handlers
    • traceback — Print or retrieve a stack traceback
    • __future__ — Future statement definitions
    • gc — Garbage Collector interface
    • inspect — Inspect live objects
    • site — Site-specific configuration hook
    • user — User-specific configuration hook
    • fpectl — Floating point exception control
    • distutils — Building and installing Python modules
  22. Custom Python Interpreters

    • code — Interpreter base classes
    • codeop — Compile Python code
  23. Restricted Execution

    • rexec — Restricted execution framework
    • Bastion — Restricting access to objects
  24. Importing Modules

    • imp — Access the import internals
    • importlib – Convenience wrappers for import()
    • imputil — Import utilities
    • zipimport — Import modules from Zip archives
    • pkgutil — Package extension utility
    • modulefinder — Find modules used by a script
    • runpy — Locating and executing Python modules
  25. Python Language Services

    • parser — Access Python parse trees
    • ast — Abstract Syntax Trees
    • symtable — Access to the compiler’s symbol tables
    • symbol — Constants used with Python parse trees
    • token — Constants used with Python parse trees
    • keyword — Testing for Python keywords
    • tokenize — Tokenizer for Python source
    • tabnanny — Detection of ambiguous indentation
    • pyclbr — Python class browser support
    • py_compile — Compile Python source files
    • compileall — Byte-compile Python libraries
    • dis — Disassembler for Python bytecode
    • pickletools — Tools for pickle developers
  26. Python compiler package

    • The basic interface
    • Limitations
    • Python Abstract Syntax
    • Using Visitors to Walk ASTs
    • Bytecode Generation
  27. Miscellaneous Services

    • formatter — Generic output formatting
  28. MS Windows Specific Services

    • msilib — Read and write Microsoft Installer files
    • msvcrt – Useful routines from the MS VC++ runtime
    • _winreg – Windows registry access
    • winsound — Sound-playing interface for Windows
  29. Unix Specific Services

    • posix — The most common POSIX system calls
    • pwd — The password database
    • spwd — The shadow password database
    • grp — The group database
    • crypt — Function to check Unix passwords
    • dl — Call C functions in shared objects
    • termios — POSIX style tty control
    • tty — Terminal control functions
    • pty — Pseudo-terminal utilities
    • fcntl — The fcntl and ioctl system calls
    • pipes — Interface to shell pipelines
    • posixfile — File-like objects with locking support
    • resource — Resource usage information
    • nis — Interface to Sun’s NIS (Yellow Pages)
    • syslog — Unix syslog library routines
    • commands — Utilities for running commands
  30. Mac OS X specific services

    • ic — Access to the Mac OS X Internet Config
    • MacOS — Access to Mac OS interpreter features
    • macostools — Convenience routines for file manipulation
    • findertools — The finder‘s Apple Events interface
    • EasyDialogs — Basic Macintosh dialogs
    • FrameWork — Interactive application framework
    • autoGIL — Global Interpreter Lock handling in event loops
    • Mac OS Toolbox Modules
    • ColorPicker — Color selection dialog

Ce notebook est une adaptation de la traduction française, dirigée par Olivier Berger et mise à jour par Henri Garreta, du tutoriel Python édité par Guido van Rossum et Fred L. Drake.