Initial commit

This commit is contained in:
2025-07-04 19:26:39 +02:00
commit c8682d4801
248 changed files with 12519 additions and 0 deletions

View File

@ -0,0 +1,6 @@
import csv
with open("demo-file-985.csv", "r", encoding="utf-8") as f:
reader = csv.reader(f)
for row in reader: # row sera une séquence, contenant un élement par colonne de la ligne en cours
print(row) # Affiche la ligne courante du CSV séparée dans une liste.

File diff suppressed because one or more lines are too long

View File

View 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()

View File

@ -0,0 +1 @@
!"#$%&'(Bonjour les amisBonjour les héros, ça va bien ?

View File

@ -0,0 +1 @@
Contenu de notre fichier texte de démo !

View 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. Lets 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. Lets 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!')
#
# Lets 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.

View 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)

View 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()

View File

View File

@ -0,0 +1,25 @@
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": [
"GML",
"XML"
]
},
"GlossSee": "markup"
}
}
}
}
}

View File

@ -0,0 +1,12 @@
import json
from os.path import dirname, join
# N'exécute le code que si vous avez spécifiquement exécuté ce module python
if __name__ == "__main__":
saisie = input("Saisissez un truc")
current_folder = dirname(__file__)
# Ouvre le fichier demo.json en lecture
f = open(join(current_folder, "demo.json"), "r", encoding="utf-8")
data = json.load(f) # Va manipuler le descripteur de fichier et renvoyer les données converties
print(type(data)) # Vérifier que le type de la donnée n'est plus juste du texte
f.close()

View File

@ -0,0 +1,26 @@
from json import dumps
# N'exécute le code que si vous avez spécifiquement exécuté ce module python
if __name__ == "__main__":
data = {
"users": [
{
"name": "Jean",
"age": 25
},
{
"name": "Denis",
"age": 30
},
{
"name": "Alice",
"age": 35
},
{
"name": "Achour",
"age": 40
}
]
}
chaine = dumps(data)
print(type(chaine))

View File

@ -0,0 +1,25 @@
DON DIÈGUE
Ô rage ! ô désespoir ! ô vieillesse ennemie !
Nai-je donc tant vécu que pour cette infamie ?
Et ne suis-je blanchi dans les travaux guerriers
Que pour voir en un jour flétrir tant de lauriers ?
Mon bras quavec respect tout lEspagne admire,
Mon bras, qui tant de fois a sauvé cet empire,
Tant de fois affermi le trône de son roi,
Trahit donc ma querelle, et ne fait rien pour moi ?
Ô cruel souvenir de ma gloire passée !
Œuvre de tant de jours en un jour effacée !
Nouvelle dignité fatale à mon bonheur !
Précipice élevé doù tombe mon honneur !
Faut-il de votre éclat voir triompher le comte,
Et mourir sans vengeance, ou vivre dans la honte ?
Comte, sois de mon prince à présent gouverneur ;
Ce haut rang nadmet point un homme sans honneur ;
Et ton jaloux orgueil par cet affront insigne
Malgré le choix du roi, men a su rendre indigne.
Et toi, de mes exploits glorieux instrument,
Mais dun corps tout de glace inutile ornement,
Fer, jadis tant à craindre, et qui, dans cette offense,
Mas servi de parade, et non pas de défense,
Va, quitte désormais le derniers des humains,
Passe, pour me venger, en de meilleurs mains.

View File

@ -0,0 +1,18 @@
"""
Base file reading example.
This example uses:
- classic open/close of file
- while loop with walrus operator (Python 3.8).
"""
if __name__ == '__main__':
file = open("../files/don-diego.txt", "r", encoding="utf-8")
# Read the file contents line by line using the walrus operator
# (introduced in Python 3.8)
# While the line read is not empty, you're not at the end of file.
while line := file.readline().strip():
# Lines contain caret return. Using `.strip()`
# removes spaces and caret returns at the start and end.
print(f"{line}")
file.close()

View File

@ -0,0 +1,16 @@
"""
Base file reading example.
This example uses:
- context manager (with ... as)
- iterator (for ... in object).
"""
if __name__ == '__main__':
with open("../files/don-diego.txt", "r", encoding="utf-8") as file:
# Read the file contents line by line
for count, line in enumerate(file):
# Lines contain caret return. Using `strip`
# removes spaces and caret returns at the start and end
# of the string.
print(f"{count} : {line.strip()}")

View File

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user data-id="101">
<nom>Zorro</nom>
<metier>Danseur</metier>
</user>
<user data-id="102">
<nom>Hulk</nom>
<metier>Footballeur</metier>
</user>
<user data-id="103">
<nom>Zidane</nom>
<metier>Star</metier>
</user>
<user data-id="104">
<nom>Beans</nom>
<metier>Epicier</metier>
</user>
<user data-id="105">
<nom>Batman</nom>
<metier>Veterinaire</metier>
</user>
<user data-id="106">
<nom>Spiderman</nom>
<metier>Veterinaire</metier>
</user>
</users>

View File

@ -0,0 +1,51 @@
from typing import List
from lxml import etree
if __name__ == "__main__":
# Balise principale
base = etree.Element("FastDMU", {"version": "2.0"})
# Balise Search system
root = etree.Element("SearchSystem")
# Deux champs pour Search System
root_title = etree.Element("Title")
root_mode = etree.Element("Mode")
root_title.text = "01"
root_mode.text = "AssembliesOnly"
root.append(root_title)
root.append(root_mode)
# Liste des items à ajouter
items: List[str] = ["A", "B", "C"]
for item in items:
# Création des éléments
search_item = etree.Element("SearchItem")
item_mode = etree.Element("Mode")
item_type = etree.Element("Type")
item_value = etree.Element("Value")
item_field = etree.Element("Field")
item_field_name = etree.Element("FieldName")
item_title = etree.Element("Title")
# Définition du texte
item_mode.text = "Add"
item_type.text = "Wildcard"
item_value.text = item
item_field.text = "PARTNUMBER"
item_field_name.text = "PARTNUMBER"
item_title.text = "Partnumber"
# Ajout des éléments au parent
search_item.append(item_mode)
search_item.append(item_type)
search_item.append(item_value)
search_item.append(item_field)
search_item.append(item_field_name)
search_item.append(item_title)
# Ajout du searchitem à la balise SearchSystem
root.append(search_item)
# Ajout de la balise SearchSystem à la balise FastDMU
base.append(root)
# J'aurais peut-être préféré faire ça avec BeautifulSoup4
# Ou peut-être gagner du temps en convertissant du texte directement
# en éléments XML.
print(etree.tostring(base, pretty_print=True, xml_declaration=True, encoding="iso8859-1",
doctype="<!DOCTYPE FastDMU>"))

View File

View File

@ -0,0 +1,17 @@
# Installer d'abord lxml avec pip install lxml
from lxml import etree
# Read content from XML file
with open("demo.xml", "rb") as file:
text = file.read()
# Read structure into Element object
structure = etree.fromstring(text)
print(type(structure))
print(structure.text)
print(structure.attrib)
for child in structure:
print(child, type(child), child.attrib)
print(structure.find("user"))