Skip to content

Commit 93d5e4e

Browse files
author
bfrerot
committed
28112025
1 parent 6e2e6ca commit 93d5e4e

9 files changed

Lines changed: 377 additions & 5 deletions

File tree

‎FILE_PROCESSING/CSV/Module-CSV.py‎

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
########## CSV MODULE ##########
2+
3+
4+
# Provides functions for reading and writing data in CSV format
5+
# Reading data is done using the reader object
6+
# Writing is done using the writer object
7+
8+
9+
10+
## .reader()
11+
# returns an object that allows us to iterate over each line in the CSV file
12+
# we need to pass a file object to the reader function. For this purpose, we can use a built-in function called open. Look at the code in the editor and run it.
13+
14+
import csv
15+
16+
with open('contacts.csv', newline='') as csvfile: # Open the CSV file
17+
reader = csv.reader(csvfile) # Create a CSV reader object
18+
print(reader)
19+
# <_csv.reader object at 0x0000018332537EE0>
20+
21+
# The output shows that the reader object has been created successfully
22+
# However, to see the actual data in the CSV file, we need to iterate over the reader object
23+
24+
#=> Iterating over the reader object
25+
import csv
26+
27+
with open('contacts.csv', newline='') as csvfile: # Open the CSV file
28+
reader = csv.reader(csvfile, delimiter=',') # Create a CSV reader object, delimiter=',' is the default
29+
for row in reader:
30+
print(row) # Iterate over each row in the CSV file and print it
31+
'''
32+
['Name', 'Phone']
33+
['mother', '222-555-101']
34+
['father', '222-555-102']
35+
['wife', '222-555-103']
36+
['mother-in-law', '222-555-104']
37+
'''
38+
39+
#=> Joining the elements of each row
40+
import csv
41+
42+
with open('contacts.csv', newline='') as csvfile:
43+
reader = csv.reader(csvfile, delimiter=',')
44+
for row in reader:
45+
print(','.join(row)) # Join the elements of each row with a comma and print
46+
'''
47+
Name,Phone
48+
mother,222-555-101
49+
father,222-555-102
50+
wife,222-555-103
51+
mother-in-law,222-555-104
52+
'''
53+
54+
#=> Using the DictReader class
55+
import csv
56+
57+
with open('contacts.csv', newline='') as csvfile:
58+
reader = csv.DictReader(csvfile) # Create a CSV DictReader object
59+
for row in reader:
60+
print(row['Name'], ':', row['Phone'])
61+
'''
62+
mother : 222-555-101
63+
father : 222-555-102
64+
wife : 222-555-103
65+
mother-in-law : 222-555-104
66+
'''
67+
68+
import csv
69+
70+
with open('contacts.csv', newline='') as csvfile:
71+
fieldnames = ['Name', 'Phone'] # Define the field names
72+
reader = csv.DictReader(csvfile, fieldnames=fieldnames) # Create a CSV DictReader object with field names
73+
for row in reader:
74+
print(row['Name'], row['Phone']) # Print the values associated with 'Name' and 'Phone'
75+
'''
76+
Name Phone
77+
mother 222-555-101
78+
father 222-555-102
79+
wife 222-555-103
80+
mother-in-law 222-555-104
81+
'''
82+
83+
84+
## writer()
85+
# Saving data to a CSV file is done using the writer object provided by the csv module
86+
# Takes the same set of arguments as the reader function
87+
88+
import csv
89+
90+
with open('exported_contacts.csv', 'w', newline='') as csvfile:
91+
writer = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) # quotechar and quoting to handle special characters
92+
# Due to csv.QUOTE_MINIMAL, this field will be automatically quoted to preserve the comma as part of the data, not as a delimiter
93+
writer.writerow(['Name', 'Phone'])
94+
writer.writerow(['mother', '222-555-101'])
95+
writer.writerow(['father', '222-555-102'])
96+
writer.writerow(['wife', '222-555-103'])
97+
writer.writerow(['mother-in-law', '222-555-104'])
98+
writer.writerow(['grandmother, grandfather', '222-555-105']) # Comma in the name
99+
# The above code creates a CSV file named exported_contacts.csv and writes the data to it
100+
# The quotechar and quoting parameters can be used to handle special characters in the data
101+
# ==> csv file
102+
'''
103+
Name,Phone
104+
mother,222-555-101
105+
father,222-555-102
106+
wife,222-555-103
107+
mother-in-law,222-555-104
108+
"grandmother, grandfather",222-555-105"
109+
'''
110+
111+
#=> quoting
112+
# specifies what values should be quoted
113+
# csv.QUOTE_MINIMAL == only values with special characters (such as delimiter or quotechar) will be quoted (default)
114+
# csv.QUOTE_ALL == quotes all values
115+
# csv.QUOTE_NONNUMERIC == quotes only non-numeric values
116+
# csv.QUOTE_NONE == doesn't quote any values. It's not a good idea to set this value if we have special characters that require quoting, because this will raise an error
117+
118+
# NOTE: The quotechar and quoting parameters can also be used in the reader function. See the documentation for more information.
119+
120+
121+
#=> fieldnames and DictWriter
122+
123+
import csv
124+
125+
with open('exported_contacts.csv', 'w', newline='') as csvfile:
126+
fieldnames = ['Name', 'Phone']
127+
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
128+
129+
writer.writeheader() # Write the header row = field names
130+
writer.writerow({'Name': 'mother', 'Phone': '222-555-101'})
131+
writer.writerow({'Name': 'father', 'Phone': '222-555-102'})
132+
writer.writerow({'Name': 'wife', 'Phone': '222-555-103'})
133+
writer.writerow({'Name': 'mother-in-law', 'Phone': '222-555-104'})
134+
writer.writerow({'Name': 'grandmother, grandfather and auntie', 'Phone': '222-555-105'})
135+
'''
136+
Name,Phone
137+
mother,222-555-101
138+
father,222-555-102
139+
wife,222-555-103
140+
mother-in-law,222-555-104
141+
"grandmother, grandfather",222-555-105"
142+
'''

‎GUI/~$inter_visual_outputs.odt‎

162 Bytes
Binary file not shown.

‎LOGGING/Module-LOGGING.py‎

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
########## LOGGING MODULE ##########
2+
3+
4+
# Python Standard Library provides a useful module called logging to log events occurring in the application
5+
# Logs are most often used to find the cause of an error
6+
# By default, Python and its modules provide many logs informing you of the causes of errors
7+
# However, it's good practice to create our own logs that may be useful to you or other programmers
8+
9+
# In Python, weu can store logs in different places
10+
# Most often it's in the form of a file
11+
# it can also be an output stream, or even an external service
12+
13+
14+
## Importing the logging module
15+
import logging
16+
17+
18+
19+
## Logger object - different ways to create loggers
20+
import logging
21+
22+
logger = logging.getLogger()
23+
hello_logger = logging.getLogger('hello')
24+
hello_world_logger = logging.getLogger('hello.world')
25+
recommended_logger = logging.getLogger(__name__)
26+
27+
28+
## Logging levels
29+
30+
#default logging levels provided by the logging module are as follows:
31+
'''
32+
Level name Value
33+
CRITICAL 50
34+
ERROR 40
35+
WARNING 30
36+
INFO 20
37+
DEBUG 10
38+
NOTSET 0
39+
'''
40+
41+
# default log format includes the level, the logger name and the message we define
42+
import logging
43+
44+
logging.basicConfig()
45+
46+
logger = logging.getLogger()
47+
48+
logger.critical('Your CRITICAL message')
49+
logger.error('Your ERROR message')
50+
logger.warning('Your WARNING message')
51+
logger.info('Your INFO message')
52+
logger.debug('Your DEBUG message')
53+
# CRITICAL:root:Your CRITICAL message
54+
# ERROR:root:Your ERROR message
55+
# WARNING:root:Your WARNING message
56+
57+
# => INFO and DEBUG messages are not shown by default because the default logging level is WARNING
58+
# To see INFO and DEBUG messages, we need to set the logging level to a lower level
59+
# This can be done by passing the setLevel method to the logger object
60+
61+
import logging
62+
63+
logging.basicConfig()
64+
65+
logger = logging.getLogger()
66+
logger.setLevel(logging.DEBUG)
67+
68+
logger.critical('Your CRITICAL message')
69+
logger.error('Your ERROR message')
70+
logger.warning('Your WARNING message')
71+
logger.info('Your INFO message')
72+
logger.debug('Your DEBUG message')
73+
'''
74+
CRITICAL:root:Your CRITICAL message
75+
ERROR:root:Your ERROR message
76+
WARNING:root:Your WARNING message
77+
INFO:root:Your INFO message
78+
DEBUG:root:Your DEBUG message
79+
'''
80+
81+
82+
## Logging to a file
83+
84+
import logging
85+
86+
logging.basicConfig(level=logging.CRITICAL, filename='prod.log', filemode='a')
87+
# basicConfig method takes three arguments
88+
# 1st = logging level equal to CRITICAL ==> only messages with this level will be processed
89+
# 2nd = passing a filename to the second argument creates a FileHandler object instead of a StreamHandler object
90+
# the logs no longer appear in the console, after setting the filename argument, all logs will be directed to the specified file
91+
# 3rd = passing the last filemode argument with the value 'a' (default mode) means that new logs will be appended to this file
92+
93+
94+
logger = logging.getLogger()
95+
96+
logger.critical('Your CRITICAL message')
97+
logger.error('Your ERROR message')
98+
logger.warning('Your WARNING message')
99+
logger.info('Your INFO message')
100+
logger.debug('Your DEBUG message')
101+
102+
# Only the CRITICAL message will be logged to the 'prod.log' file
103+
# files contains:
104+
'''
105+
CRITICAL:root:Your CRITICAL message
106+
'''
107+
108+
109+
## Logging with a specific format
110+
111+
import logging # import the logging module
112+
113+
FORMAT = '%(name)s:%(levelname)s:%(asctime)s:%(message)s' # define the log format
114+
115+
logging.basicConfig(level=logging.CRITICAL, filename='prod.log', filemode='a', format=FORMAT) # configure logging to write to 'prod.log' with CRITICAL level and specified format
116+
117+
logger = logging.getLogger() # get the root logger
118+
119+
logger.critical('Your CRITICAL message')
120+
logger.error('Your ERROR message')
121+
logger.warning('Your WARNING message')
122+
logger.info('Your INFO message')
123+
logger.debug('Your DEBUG message')
124+
'''
125+
CRITICAL:root:Your CRITICAL message
126+
root:CRITICAL:2025-11-21 07:40:51,630:Your CRITICAL message
127+
root:CRITICAL:2025-11-21 07:40:54,991:Your CRITICAL message
128+
root:CRITICAL:2025-11-21 07:41:10,462:Your CRITICAL message
129+
root:CRITICAL:2025-11-24 08:12:40,642:Your CRITICAL message
130+
'''

‎LOGGING/test_logger.py‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import logging
2+
3+
# Configuration du format de log
4+
FORMAT = '%(name)s:%(levelname)s:%(asctime)s:%(message)s'
5+
6+
# Configuration du logging avec niveau DEBUG pour capturer tous les messages
7+
logging.basicConfig(
8+
level=logging.DEBUG,
9+
filename='user_activity.log',
10+
filemode='a',
11+
format=FORMAT
12+
)
13+
14+
# Récupération du logger
15+
logger = logging.getLogger('UserLogger')
16+
17+
def log_user_input(user_message):
18+
"""
19+
Génère un log en fonction du message de l'utilisateur
20+
"""
21+
logger.info(f"Message reçu de l'utilisateur: {user_message}")
22+
23+
# Logique simple pour démonstration
24+
if len(user_message) == 0:
25+
logger.warning("Message vide détecté!")
26+
elif len(user_message) > 100:
27+
logger.warning(f"Message très long ({len(user_message)} caractères)")
28+
elif "erreur" in user_message.lower():
29+
logger.error(f"Mot-clé 'erreur' détecté: {user_message}")
30+
elif "critique" in user_message.lower():
31+
logger.critical(f"Situation critique signalée: {user_message}")
32+
else:
33+
logger.debug(f"Message normal traité: {user_message[:50]}...")
34+
35+
# Programme principal
36+
if __name__ == "__main__":
37+
print("=== Système de logging simple ===")
38+
print("Tapez vos messages (tapez 'quit' pour quitter)\n")
39+
40+
while True:
41+
user_input = input("Votre message: ")
42+
43+
if user_input.lower() == 'quit':
44+
logger.info("Programme terminé par l'utilisateur")
45+
print("\nLogs enregistrés dans 'user_activity.log'")
46+
break
47+
48+
log_user_input(user_input)
49+
print("✓ Message enregistré dans le log\n")

‎SandBox.py‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1-
import xml.etree.ElementTree as ET
1+
from turtle import *
22

3-
root = ET.Element('data')
4-
movie_1 = ET.SubElement(root, 'movie', {'title': 'The Little Prince', 'rate': '5'})
5-
movie_2 = ET.SubElement(root, 'movie', {'title': 'Hamlet', 'rate': '5'})
6-
ET.dump(root)
3+
color('pink')
4+
speed(10)
5+
6+
for i in range (150):
7+
forward(100)
8+
left(112)

‎contacts.csv‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Name,Phone
2+
mother,222-555-101
3+
father,222-555-102
4+
wife,222-555-103
5+
mother-in-law,222-555-104

‎exported_contacts.csv‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
Name,Phone
2+
mother,222-555-101
3+
father,222-555-102
4+
wife,222-555-103
5+
mother-in-law,222-555-104
6+
"grandmother, grandfather and auntie",222-555-105

‎prod.log‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
CRITICAL:root:Your CRITICAL message
2+
root:CRITICAL:2025-11-21 07:40:51,630:Your CRITICAL message
3+
root:CRITICAL:2025-11-21 07:40:54,991:Your CRITICAL message
4+
root:CRITICAL:2025-11-21 07:41:10,462:Your CRITICAL message
5+
root:CRITICAL:2025-11-24 08:12:40,642:Your CRITICAL message
6+
root:CRITICAL:2025-11-24 09:11:06,363:Your CRITICAL message

‎user_activity.log‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
UserLogger:INFO:2025-11-24 09:08:44,310:Message re�u de l'utilisateur: C:\Python313\python.exe c:/PythonLearning/SandBox.py
2+
UserLogger:DEBUG:2025-11-24 09:08:44,312:Message normal trait�: C:\Python313\python.exe c:/PythonLearning/SandBox....
3+
UserLogger:INFO:2025-11-24 09:08:46,135:Message re�u de l'utilisateur: C:\Python313\python.exe c:/PythonLearning/SandBox.py
4+
UserLogger:DEBUG:2025-11-24 09:08:46,135:Message normal trait�: C:\Python313\python.exe c:/PythonLearning/SandBox....
5+
UserLogger:INFO:2025-11-24 09:09:52,829:Message re�u de l'utilisateur: C:\Python313\python.exe c:/PythonLearning/SandBox.py
6+
UserLogger:DEBUG:2025-11-24 09:09:52,830:Message normal trait�: C:\Python313\python.exe c:/PythonLearning/SandBox....
7+
UserLogger:INFO:2025-11-24 09:10:48,215:Message re�u de l'utilisateur: C:\Python313\python.exe c:/PythonLearning/SandBox.py
8+
UserLogger:DEBUG:2025-11-24 09:10:48,215:Message normal trait�: C:\Python313\python.exe c:/PythonLearning/SandBox....
9+
UserLogger:INFO:2025-11-24 09:10:49,861:Message re�u de l'utilisateur: C:\Python313\python.exe c:/PythonLearning/SandBox.py
10+
UserLogger:DEBUG:2025-11-24 09:10:49,862:Message normal trait�: C:\Python313\python.exe c:/PythonLearning/SandBox....
11+
UserLogger:INFO:2025-11-24 09:10:52,059:Message re�u de l'utilisateur: C:\Python313\python.exe c:/PythonLearning/SandBox.py
12+
UserLogger:DEBUG:2025-11-24 09:10:52,059:Message normal trait�: C:\Python313\python.exe c:/PythonLearning/SandBox....
13+
UserLogger:INFO:2025-11-24 09:10:53,566:Message re�u de l'utilisateur: C:\Python313\python.exe c:/PythonLearning/SandBox.py
14+
UserLogger:DEBUG:2025-11-24 09:10:53,567:Message normal trait�: C:\Python313\python.exe c:/PythonLearning/SandBox....
15+
UserLogger:INFO:2025-11-24 09:10:53,765:Message re�u de l'utilisateur: C:\Python313\python.exe c:/PythonLearning/SandBox.py
16+
UserLogger:DEBUG:2025-11-24 09:10:53,765:Message normal trait�: C:\Python313\python.exe c:/PythonLearning/SandBox....
17+
UserLogger:INFO:2025-11-24 09:10:53,927:Message re�u de l'utilisateur: C:\Python313\python.exe c:/PythonLearning/SandBox.py
18+
UserLogger:DEBUG:2025-11-24 09:10:53,928:Message normal trait�: C:\Python313\python.exe c:/PythonLearning/SandBox....
19+
UserLogger:INFO:2025-11-24 09:10:54,094:Message re�u de l'utilisateur: C:\Python313\python.exe c:/PythonLearning/SandBox.py
20+
UserLogger:DEBUG:2025-11-24 09:10:54,094:Message normal trait�: C:\Python313\python.exe c:/PythonLearning/SandBox....
21+
UserLogger:INFO:2025-11-24 09:10:54,314:Message re�u de l'utilisateur: C:\Python313\python.exe c:/PythonLearning/SandBox.py
22+
UserLogger:DEBUG:2025-11-24 09:10:54,315:Message normal trait�: C:\Python313\python.exe c:/PythonLearning/SandBox....
23+
UserLogger:INFO:2025-11-24 09:10:56,489:Message re�u de l'utilisateur: C:\Python313\python.exe c:/PythonLearning/SandBox.py
24+
UserLogger:DEBUG:2025-11-24 09:10:56,489:Message normal trait�: C:\Python313\python.exe c:/PythonLearning/SandBox....
25+
UserLogger:INFO:2025-11-24 09:11:18,543:Message re�u de l'utilisateur: C:\Python313\python.exe c:/PythonLearning/LOGGING/test_logger.py
26+
UserLogger:DEBUG:2025-11-24 09:11:18,543:Message normal trait�: C:\Python313\python.exe c:/PythonLearning/LOGGING/...
27+
UserLogger:INFO:2025-11-24 09:11:20,117:Message re�u de l'utilisateur: C:\Python313\python.exe c:/PythonLearning/LOGGING/test_logger.py
28+
UserLogger:DEBUG:2025-11-24 09:11:20,117:Message normal trait�: C:\Python313\python.exe c:/PythonLearning/LOGGING/...
29+
UserLogger:INFO:2025-11-24 09:11:23,634:Message re�u de l'utilisateur: C:\Python313\python.exe c:/PythonLearning/LOGGING/test_logger.py
30+
UserLogger:DEBUG:2025-11-24 09:11:23,634:Message normal trait�: C:\Python313\python.exe c:/PythonLearning/LOGGING/...
31+
UserLogger:INFO:2025-11-24 09:11:36,826:Message re�u de l'utilisateur:
32+
UserLogger:WARNING:2025-11-24 09:11:36,826:Message vide d�tect�!

0 commit comments

Comments
 (0)