Initial commit
This commit is contained in:
0
source/08-text-files/fileuse/__init__.py
Normal file
0
source/08-text-files/fileuse/__init__.py
Normal file
42
source/08-text-files/fileuse/binaryfile.py
Normal file
42
source/08-text-files/fileuse/binaryfile.py
Normal file
@ -0,0 +1,42 @@
|
||||
|
||||
def write_file():
|
||||
"""
|
||||
Écrire un fichier binaire très simple.
|
||||
|
||||
En Python, on ne peut pas tout simplement écrire des chaînes dans un
|
||||
fichier dit binaire. Dans Python 3, on fait la différence entre binaire et texte.
|
||||
Quand on manipule des fichiers texte, on peut y écrire des données `str`.
|
||||
Par contre, quand on manipule des fichiers binaires, on manipule des données plus
|
||||
brutes, de type `bytes` (ou `bytearray`)
|
||||
|
||||
"""
|
||||
f = open("demo.bin", "wb")
|
||||
f.write(bytearray([32, 33, 34, 35, 36, 37, 38, 39, 40])) # (9)
|
||||
f.write(b"Bonjour les amis") # (16) ça passe car les caractères sont ASCII et leur code tient dans un byte
|
||||
f.write("Bonjour les héros, ça va bien ?".encode("utf-8")) # (33)
|
||||
f.close()
|
||||
|
||||
|
||||
def read_file():
|
||||
"""
|
||||
Lire dans un fichier binaire très simple.
|
||||
|
||||
"""
|
||||
f = open("demo.bin", "rb")
|
||||
tableau = f.read(9)
|
||||
chaine1 = f.read(16)
|
||||
chaine2 = f.read(33).decode("utf-8")
|
||||
f.seek(0)
|
||||
data = f.read()
|
||||
f.close()
|
||||
# Afficher les données lues dans le fichier
|
||||
print(tableau)
|
||||
print(chaine1)
|
||||
print(chaine2)
|
||||
# Pour tester, revenir au début du fichier et tout lire d'une traite
|
||||
print(data)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
write_file()
|
||||
read_file()
|
1
source/08-text-files/fileuse/demo.bin
Normal file
1
source/08-text-files/fileuse/demo.bin
Normal file
@ -0,0 +1 @@
|
||||
!"#$%&'(Bonjour les amisBonjour les héros, ça va bien ?
|
1
source/08-text-files/fileuse/demo.txt
Normal file
1
source/08-text-files/fileuse/demo.txt
Normal file
@ -0,0 +1 @@
|
||||
Contenu de notre fichier texte de démo !
|
43
source/08-text-files/fileuse/filemanager.py
Normal file
43
source/08-text-files/fileuse/filemanager.py
Normal file
@ -0,0 +1,43 @@
|
||||
|
||||
with open("demo.txt", "r", encoding="utf-8") as f:
|
||||
pass
|
||||
|
||||
# écrire un manager
|
||||
class File(object):
|
||||
def __init__(self, file_name, method):
|
||||
self.file_obj = open(file_name, method)
|
||||
def __enter__(self):
|
||||
return self.file_obj
|
||||
def __exit__(self, type, value, traceback):
|
||||
self.file_obj.close()
|
||||
|
||||
# Just by defining __enter__ and __exit__ methods we can use our new class in a with statement. Let’s try:
|
||||
#
|
||||
# with File('demo.txt', 'w') as opened_file:
|
||||
# opened_file.write('Hola!')
|
||||
#
|
||||
# Our __exit__ method accepts three arguments. They are required by every __exit__ method which is a part of a Context Manager class. Let’s talk about what happens under-the-hood.
|
||||
#
|
||||
# The with statement stores the __exit__ method of the File class.
|
||||
# It calls the __enter__ method of the File class.
|
||||
# The __enter__ method opens the file and returns it.
|
||||
# The opened file handle is passed to opened_file.
|
||||
# We write to the file using .write().
|
||||
# The with statement calls the stored __exit__ method.
|
||||
# The __exit__ method closes the file.
|
||||
|
||||
|
||||
# We did not talk about the type, value and traceback arguments of the __exit__ method. Between the 4th and 6th step, if an exception occurs, Python passes the type, value and traceback of the exception to the __exit__ method. It allows the __exit__ method to decide how to close the file and if any further steps are required. In our case we are not paying any attention to them.
|
||||
#
|
||||
# What if our file object raises an exception? We might be trying to access a method on the file object which it does not supports. For instance:
|
||||
#
|
||||
# with File('demo.txt', 'w') as opened_file:
|
||||
# opened_file.undefined_function('Hola!')
|
||||
#
|
||||
# Let’s list the steps which are taken by the with statement when an error is encountered:
|
||||
#
|
||||
# It passes the type, value and traceback of the error to the __exit__ method.
|
||||
# It allows the __exit__ method to handle the exception.
|
||||
# If __exit__ returns True then the exception was gracefully handled.
|
||||
# If anything other than True is returned by the __exit__ method then the exception is raised by the with statement.
|
||||
|
12
source/08-text-files/fileuse/filesearch.py
Normal file
12
source/08-text-files/fileuse/filesearch.py
Normal file
@ -0,0 +1,12 @@
|
||||
import os, glob
|
||||
|
||||
# traverse root directory, and list directories as dirs and files as files
|
||||
for root, dirs, files in os.walk("/home/steve/Code/python/initiation"):
|
||||
for filename in files:
|
||||
path = os.path.join(root, filename)
|
||||
print(path)
|
||||
|
||||
|
||||
# https://docs.python.org/fr/3/library/glob.html
|
||||
files = glob.glob("/home/steve/Code/python/initiation/**/*.py", recursive=True)
|
||||
print(files)
|
25
source/08-text-files/fileuse/textfile.py
Normal file
25
source/08-text-files/fileuse/textfile.py
Normal file
@ -0,0 +1,25 @@
|
||||
|
||||
def write_file():
|
||||
"""
|
||||
Écrire un fichier texte très simple.
|
||||
|
||||
"""
|
||||
f = open("demo.txt", "w")
|
||||
f.write("Contenu de notre fichier texte de démo e!")
|
||||
f.close()
|
||||
|
||||
|
||||
def read_file():
|
||||
"""
|
||||
Lire dans un fichier texte très simple.
|
||||
|
||||
"""
|
||||
f = open("demo.txt", "r")
|
||||
data = f.read()
|
||||
f.close()
|
||||
print(data)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
write_file()
|
||||
read_file()
|
Reference in New Issue
Block a user