0% found this document useful (0 votes)
6 views

Chapitre Module FileProcessing

Uploaded by

Yosr Yo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Chapitre Module FileProcessing

Uploaded by

Yosr Yo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Ch3: Modules et packages

Sonia Gharsalli
Plan
 Syntaxe
 Module math
 Module random
 Module datetime
 Module time
 Module calendar
 Module os
 File processing
Définition

 Les modules sont des programmes Python qui contiennent des fonctions que l’on est amené à
réutiliser souvent (on les appelle aussi bibliothèques ou libraries). Ce sont des « boîtes à outils » qui
vont vous être très utiles.
 Prenez toujours le réflexe de vérifier si une partie du code que vous souhaitez écrire n’existe pas déjà
sous forme de module.
Syntaxe
• Appel de plusieurs modules

• Utilisation de fonction et de
données définit dans le
module
• Importation de toutes les fonctions et les
données dans le module « my_module »

• Importation avec des alias


Les modules prédéfinies

 Pour connaitre les entités présentes dans un module, on peut utiliser la fonction dir().
 Elle retourne une liste des entités
Module math
Tapez le code suivant et analysez les fonction et les données appeler :
Tapez le code suivant, quel est la différence entre ceil, floor et trunc
•ceil(x) → the ceiling of x (the smallest integer greater than or equal to x)
•floor(x) → the floor of x (the largest integer less than or equal to x)
•trunc(x) → the value of x truncated to an integer (be careful - it's not an equivalent either
of ceil or floor)
•factorial(x) → returns x! (x has to be an integral and not a negative)
•hypot(x, y) → returns the length of the hypotenuse of a right-angle triangle with the leg
lengths equal to x and y (the same as sqrt(pow(x, 2) + pow(y, 2)) but more precise)
 Tapez le code suivant que remarquez-vous

La définition de la fonction exp() redéfinit la fonction existante déjà dans le module math.
Module random
 The most general function named random() (not to be confused with the
module's name).
 Produces a float number x coming from the range (0.0, 1.0) - in other
words: (0.0 <= x < 1.0).

Tapez le code suivant et exécutez le deux fois


 Tapez le code suivant et exécutez le deux fois, que remarquez-vous?
Valeur entière aléatoire

It will generate an integer taken (pseudorandomly) from the range


(respectively):
•range(end)
•range(beg, end)
•range(beg, end, step)
 Note the implicit right-sided exclusion!

The last function is an equivalent of randrange(left, right+1)


It generates the integer value i, which falls in the range [left, right] (no
exclusion on the right side).
Random à partir d’une liste

It's a function named in a very suggestive way - choice:


•choice(sequence)
•sample(sequence, elements_to_choose)
The first variant chooses a "random" element from the input sequence and returns it.
The second one builds a list (a sample) consisting of the elements_to_choose element "drawn" from the
input sequence.
In other words, the function chooses some of the input elements, returning a list with the choice. The
elements in the sample are placed in random order. Note: the elements_to_choose must not be greater
than the length of the input sequence.
Exercice :
Écrivez un programme en Python qui simule un jeu de devinette où l'ordinateur choisit un nombre
entier aléatoire entre 1 et 100, et le joueur doit deviner ce nombre en un nombre limité d'essais (5).
Demandez à l'utilisateur d'entrer ses devinettes à chaque tour et lui indiquer s'il est trop haut, trop
bas ou s'il a deviné correctement. À la fin de chaque version du jeu, affichez le nombre de devinettes
utilisées et si le joueur a réussi à deviner le nombre ou non.
Module datetime
 From datetime import date
 Import time
 From datetime import time
 From datetime import datetime
Module datetime

date : is a calss provided by datetime module. Objects of this class represent a date consisting of
the year, month, and day.
date.today():

date.fromisoformat()
date.replace() : the method returns a changed date object, so you must remember to assign it to some
variable.

date.strftime() : All datetime module classes presented so far have a method called strftime. This is a
very important method, because it allows us to return a string of the date and time in the format we
specify.
Link for more directives https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
date.weekday(): It returns the day of the week as an integer, where 0 is Monday and 6 is Sunday

time : The datetime module has a class that allows you to present time.
datetime : In the datetime module, date and time can be represented as separate objects or as one.
The class that combines date and time is called datetime.

timestamp : The timestamp method returns a float value expressing the number of seconds elapsed
between the date and time indicated by the datetime object and January 1, 1970, 00:00:00 (UTC).
The strptime() : method requires you to specify the format in which you saved the date and time.

timedelta : timedelta object can be returned as a result of subtracting two date or datetime objects.
Module time
The time function returns the number of seconds from January 1, 1970 to the current moment in the
form of a float number.

time.sleep()
Module Calendar

 calendar.setfirstweekday(): change this behavior of the representation of the month


weekday, which returns the day of the week as an integer value for the given year, month, and day

Isleap : returns True if the passed year is leap, or False otherwise.


Leapdays: returns the number of leap years in the given range of years.
Module os
 mkdir() : The mkdir() function creates a directory in the specified path. Note that
running the program twice will raise a FileExistsError.
 makedirs (): The makedirs function enables recursive directory creation, which
means that all directories in the path will be created.
 Listdir() : The listdir function returns a list containing the names of the files and
directories that are in the path passed as an argument.
 os.chdir() : changes the current working directory to the specified path. As an
argument, it takes any relative or absolute path.
 getcwd() : returns information about the current working directory.
 os.rmdir() : delete a single directory. The path is passed as its argument.
 os.removedirs():Remove a directory and its subdirectories. The function
requires you to specify a path containing all directories that should be removed.
 Quel sera la sortie de ce code
File processing
Files

 Files are named locations on disk to store related information. They are used to
permanently store data in a non-volatile memory (e.g. hard disk).
 When we want to read from or write to a file, we need to open it first. When we are
done, it needs to be closed so that the resources that are tied with the file are freed.
 File operation takes place in the following order:
➢ Open a file
➢ Read or write (perform operation)
➢ Close the file
Types Of File in Python

There are two types of files in Python


 Binary file
 Text file
Binary files in Python

All binary files follow a specific format. We can open some binary files in the normal text
editor but we can’t read the content present inside the file. That’s because all the binary files
will be encoded in the binary format, which can be understood only by a computer or
machine.
 For handling such binary files we need a specific type of software to open it.

For Example, You need Microsoft word software to open .doc binary files. Likewise, you need
a pdf reader software to open .pdf binary files, and so on…
Binary files in Python
Most of the files that we see in our computer system are called binary files.
 Example:
• Document files: .pdf, .doc, .xls etc.
• Image files: .png, .jpg, .gif, .bmp etc.
• Video files: .mp4, .3gp, .mkv, .avi etc.
• Audio files: .mp3, .wav, .mka, .aac etc.
• Database files: .mdb, .accde, .frm, .sqlite etc.
• Archive files: .zip, .rar, .iso, .7z etc.
• Executable files: .exe, .dll, .class etc
Text files

 A text file is usually considered as sequence of lines. Line is a sequence of characters (ASCII),
stored on permanent storage media. Although default character coding in python is ASCII but
supports Unicode as well.
 in text file, each line is terminated by a special character, known as End of Line (EOL). From
strings we know that \n is newline character.
 Text files don’t have any specific encoding and it can be opened in normal text editor itself.
Example:
• Web standards: html, XML, CSS, JSON etc.
• Source code: c, app, js, py, java etc.
• Documents: txt, tex, RTF etc.
• Tabular data: csv, tsv etc.
• Configuration: ini, cfg, reg etc.
Opening or Creating a New File

 The method open() is used to open an existing file or creating a new file. If the complete
directory is not given then the file will be created in the directory in which the python file
is stored. The syntax for using open() method is given below.

 The open method returns file object which can be stored in the name file_object (file-
handle).
 File name is a unique name in a directory. The open() function will create the file with the
specified name (in write mode) if it is not already exists otherwise it will open the
already existing file.
 The access mode it is the string which tells in what mode the file should be opened for
operations.
There are three different access modes are available in python.
• Reading: Reading mode is crated only for reading the file. The pointer will be at the beginning of
the file.
• Writing: Writing mode is used for overwriting the information on existing file.
• Append: Append mode is same as the writing mode. Instead of over writing the information this
mode append the information at the end.
Access modes in Text Files
• ‘r' – Read Mode: Read mode is used only to read data from the file.
• ‘w' – Write Mode: This mode is used when you want to write data into the file or modify it.
Remember write mode overwrites the data present in the file.
• ‘a' – Append Mode: Append mode is used to append data to the file. Remember data will be
appended at the end of the file pointer.
• ‘r+' – Read or Write Mode: This mode is used when we want to write or read the data from the
same file.
• ‘a+' – Append or Read Mode: This mode is used when we want to read data from the file or
append the data into the same file.
Access modes in Binary Files
• ‘wb’ – Open a file for write only mode in the binary format.
• ‘rb’ – Open a file for the read-only mode in the binary format.
• ‘ab’ – Open a file for appending only mode in the binary format.
• ‘rb+’ – Open a file for read and write only mode in the binary format.
• ‘ab+’ – Open a file for appending and read-only mode in the binary format.
Buffering
Buffering is the process of storing a chunk of a file in a temporary memory until the file loads
completely. In python there are different values can be given.
If the buffering is set to 0 , then the buffering is off. The buffering will be set to 1 when we need to
buffer the file.
Opening Files
Closing Files

 After processing the content in a file, the file must be saved and closed. To do this we can
use another method close() for closing the file. This is an important method to be
remembered while handling files in python
Reading Information in the File

 In order to read a file in python, we must open the file in read mode.
 There are three ways in which we can read the files in python.
– read([n])
– readline([n])
– readlines() : all lines returned to a list

• Here, n is the number of bytes to be read


Write to a Python File
 In order to write data into a file, we must open the file in write mode.
 We need to be very careful while writing data into the file as it overwrites the content
present inside the file that you are writing, and all the previous data will be erased.
We have two methods for writing data into a file as shown below.
➢ write(string)
➢ writelines(list)
Append in a Python File
B i n a r y f i l e o p e ra t i o n s

 If we want to write a structure such as list or dictionary to a file and read it subsequently
we need to use the Python module pickle.
 Pickling is the process of converting structure to a byte stream before writing to a file and
while reading the content of file a reverse process called Unpickling is used to convert the
byte stream back to the original format.

You might also like