20. Librairies utiles¶
20.1. Module os¶
>>> import os
>>> os.getcwd()
'/Users/laurentpaoletti/Documents/WRK/PRJ/Cours python ISEN/Seance 2'
>>> os.listdir(os.curdir)
['.DS_Store', 'classes.rst', 'libraries.rst', 'myui.py', 'myui.pyc', 'myui.ui', 'pyside.rst', 'pyside1.py', 'pysid
e2.py', 'pyside3.py', 'pyside4.py', 'pyside_creator.py', 'tk1.Py', 'tk2.Py', 'tk3.py', 'tk4.py', 'tk5.py', 'tk6.py
', 'tk7.py', 'tkinter.rst']
>>> os.name
'posix'
20.2. Pathname manipulation¶
>>> print (os.path.join('path' ,'to', 'my', 'dir'))
path/to/my/dir
>>> os.path.exists('/Users/me/file.txt')
True
>>> os.path.isdir('/Users/me/')
True
>>> os.path.isfile('/Users/me/file.txt')
True
20.3. Parcourir une arborescence¶
>>> for root, dirs, files in os.walk(os.curdir):
... print("{0} has {1} files".format(root, len(files)))
20.4. Fichiers¶
Ouvrir un fichier
>>> file_object = open('myfile', 'r') #en lecture
>>> line = file_object.readline()
Mode d’ouverture
w overwrite
a ajout
w+ lecture ecriture, overwrite
a+ lecture ecriture, ajout
fermer un fichier
>>> file_object.close()
Ouvrir en ecriture
>>> file_object = open("myfile", 'w') #en ecriture
>>> file_object.write(“Hello, World\n”)
>>> file_object.close()
Lire un fichier
>>> file_object = open("myfile", 'r')
>>> count = 0
>>> while file_object.readline() != "":
>>> count = count + 1 print(count)
>>> file_object.close()
Avec un context manager
>>> with open('workfile', 'r') as f:
... read_data = f.read()
Ecrire des lignes à la suite
>>> file_object = open("hello.txt", "w")
>>> lines_of_text = ["a line of text", "another line of text", "a third line"]
>>> file_object.writelines(lines_of_text)
20.5. Cryptographie¶
>>> import hashlib
>>> data = "Lorem ipsum dolor sit amet, consectetur adipisicing elit"
>>> h = hashlib.md5()
>>> h.update(data)
>>> h.hexdigest()
'1a16b08270f1994e35ee1d6a42478f13'
>>> h2 = hashlib.sha1()
>>> h2.update(data)
>>> h2.hexdigest()
'b71d554ddfdf8e6a2518b4eacc93dcb06952ee5e'
20.6. Mathematics¶
>>> import math
>>> math.sin(0)
0.0
>>> math.sin(math.radians(90))
1.0
20.7. random¶
>>> import random
>>> random.randint(1, 100)
87
random système (mieux)
>>> r = random.SystemRandom()
>>> r.random()
0.4599472067935497
20.8. Pickle¶
Attention: sécurité
Ecriture
>>> import pickle
>>> file = open("state", 'w')
>>> pickle.dump(a, file)
>>> pickle.dump(b, file)
>>> pickle.dump(c, file)
>>> file.close()
Lecture
>>> import pickle
>>> file = open('pickled', 'r')
>>> a = pickle.load(file)
>>> a
'foo'