Vous êtes sur la page 1sur 46

Intro.py Operations.py File_Object.. File_naviga.. Libraries.

py

1
2
3
Programming ‘Python’ {
4
5 ‘Title’ : [ “ File Handling ” ]
6
7 ‘Made_By’ : [
8 “ Youssef Jabri ”
9 “ Othmane Sadiky ”
10 “ Hamza Fellah ”
11
]
12
13 }
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

1
2
Programming ‘Python’ {
3
4 01 Les Opérations : [‘Ouvrir’,’Lire’,’Ecrire’]

5
6
02 Les Propriétés d'Objet “ File ”
7
8
9 03 Navigation Dans Un Fichier : [‘seek()’,’tell()’]
10
11
12 04 Les bibliothèques : [‘os’, ‘shutil’]
13
14 }
Programming Language : PYTHON
Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

1
2
3
Introduction {
4
5 Gestion de Fichiers :
6
7
8 < En informatique, la gestion de fichiers consiste à manipuler des fichiers, que ce
9 soit pour les lire, écrire, ou effectuer d'autres opérations >
10
11
12
13 }
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

1
2
3
Introduction {
4
5 Types de Fichiers :
6
7 <F1> Fichier .txt </F1>
8
9 <F2> Fichier .csv </F2>
10
11 <F3> Fichier .json </F3>
12
13 }
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

1
2
3 01 {
4
5
6

Les Opérations : []
7
8
9
10
11

}
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

01 {
1
2
3
4
5
Les Opérations : [‘Ouvrir’]
6
7 Pour interagir avec un fichier en Python, on utilise la fonction open() :
8
9
10
11
12 Elle prend deux paramètres : le nom du fichier et le mode. Il existe quatre
13 méthodes différentes (modes) pour ouvrir un fichier :
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

01 {
1
2
3
4
5
Les Opérations : [‘Ouvrir’]
6
"r" {Lecture} : Valeur par défaut. Ouvre un fichier en lecture, génère une erreur si
7
le fichier n'existe pas.
8
9
10
11
"a" {Ajout} : Ouvre un fichier en mode ajout, crée le fichier s'il n'existe pas.
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

01 {
1
2
3
4
5
Les Opérations : [‘Ouvrir’]
6
7 "w" {Écriture} : Ouvre un fichier en mode écriture, crée le fichier s'il n'existe pas.
8
9
10
11
"x" {Création} : Crée le fichier spécifié, renvoie une erreur si le fichier existe.
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

01 {
1
2
3
4
5
Les Opérations : [‘Lire’]
6
7 La méthode read() permet de lire le contenu d'un fichier en Python. Lorsque
8 vous utilisez cette méthode, elle renvoie tout le contenu du fichier sous forme de
9
chaîne de caractères.
10
11
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

01 {
1
2
3
4
5
Les Opérations : [‘Lire’]
6
7 Par défaut, la méthode read() retourne l'intégralité du texte, mais vous pouvez
8 également spécifier le nombre de caractères que vous souhaitez obtenir :
9
10
11
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

01 {
1
2
3
4
5
Les Opérations : [‘Lire’]
6
7
Les erreurs peuvent survenir lors de la lecture ou de l’écriture dans un fichier ou
comme il est très facile d’oublier d’appeler la méthode close(), Python fournit
8
une syntaxe spéciale : ‘with’
9
10
11
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

01 {
1
2
3
4
5
Les Opérations : [‘Lire’]
6
7 Vous pouvez obtenir une seule ligne en utilisant la méthode readline() :
8
9
10
11
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

01 {
1
2
3
4
5
Les Opérations : [‘Lire’]
6
7 Vous pouvez obtenir une List ligne par ligne en utilisant la méthode readlines() :
8
9
10
11
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

01 {
1
2
3
4
5
Les Opérations : [‘Lire’]
6
7 Parcourir le fichier ligne par ligne :
8
9
10
11
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

01 {
1
2
3
4
5
Les Opérations : [‘Lire’]
6
7 Lire un fichier csv :
8
9
10
11
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

01 {
1
2
3
4
5
Les Opérations : [‘Lire’]
6
7 Lire un fichier csv :
8
9
10
11
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

01 {
1
2
3
4
5
Les Opérations : [‘Ecrire’]
6
Pour écrire dans un fichier existant, vous devez ajouter un paramètre à la
7 fonction open() :
8
9
10 "a" {Ajout} : ajoutera à la fin du fichier
11
12
13 "w" {Écriture} : écrasera tout contenu existant
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

01 {
1
2
3
4
5
Les Opérations : [‘Ecrire’]
6
Write() :
7
8
9
10
11
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

01 {
1
2
3
4
5
Les Opérations : [‘Ecrire’]
6
Writelines() :
7
8
9
10
11
12
13
14 }
Programming Language : PYTHON
Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

1
2
3 02 {
4
5
6
7
8
9
Les Propriétés d'Objet “ File ”
10
11

}
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

02 {
1
2
3
4
5
Les Propriétés d'Objet “ File ” :
6
7
8 L'objet Fichier offre des attributs permettant d'accéder à des détails d'un fichier,
9
10
notamment son nom et le mode d'ouverture. Ces attributs offrent une manière
11 pratique d'obtenir des informations sur le fichier en cours de traitement.
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

02 {
1
2
3
4
5
Les Propriétés d'Objet “ File ” :
6
<P1> Fichier.name </P1> :
7
8
9 Renvoie le nom du fichier en lecture seule .Si l'objet fichier a été créé avec la
10
fonction open(), il renvoie le nom du fichier, sinon, il indique la source de l'objet
11
12 fichier sous forme de chaîne.
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

02 {
1
2
3
4
5
Les Propriétés d'Objet “ File ” :
6
<P2> Fichier.encoding </P2> :
7
8
9 Renvoie l'encodage utilisé par ce fichier. Lorsque les chaînes Unicode sont écrites
10
dans un fichier, elles seront converties en chaînes d'octets. Il peut également être
11
12 None. Dans ce cas, le fichier utilise l'encodage par défaut du système pour convertir
13 les chaînes Unicode.
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

02 {
1
2
3
4
5
Les Propriétés d'Objet “ File ” :
6
<P3> Fichier.mode </P3> :
7
8
9 Renvoie le mode d'accès au fichier utilisé lors de l'ouverture d'un fichier.
10
11 <P4> Fichier.closed </P4> :
12
13 Renvoie True si un fichier est fermé.
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

02 {
1
2
3
4
5
Les Propriétés d'Objet “ File ” :
6
7
8
9
10
11
12
13
14
}
Programming Language : PYTHON
Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

1
2
3 03 {
4
5
6
7
8
9
Navigation Dans Un Fichier []
10
11

}
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

03 {
1
2
3
4
5
Navigation Dans Un Fichier : [‘Seek()’]
6
7 Méthode des objets fichiers. Elle est utilisée pour déplacer la position du curseur
8
de lecture/écriture dans un fichier. La syntaxe générale est la suivante :
9
10
11
12
13
< Fichier.seek(déplacement, mode) >
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

03 {
1
2
3
4
5
Navigation Dans Un Fichier : [‘Seek()’]
6
7
Déplacement : Le déplacement spécifie le nombre d'octets à déplacer. Un
8
9 déplacement positif déplace le curseur vers l'avant, et un déplacement négatif le
10 déplace vers l'arrière.
11
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

03 {
1
2
3
4
5
Navigation Dans Un Fichier : [‘Seek()’]
6
7 Mode : Le mode spécifie à partir d'où le déplacement doit être effectué. Les
8 valeurs courantes sont :
9
10
< 0 > : à partir du début du fichier (défaut).
11
12 < 1 > : à partir de la position actuelle du curseur.
13
< 2 > : à partir de la fin du fichier.
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

03 {
1
2
3
4
5
Navigation Dans Un Fichier : [‘Seek()’]
6
7
8
9
10
11
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

03 {
1
2
3
4
5
Navigation Dans Un Fichier : [‘Tell()’]
6
7
8 Retourne la position actuelle du curseur dans le fichier. Elle est utilisée pour
9
déterminer la position à laquelle se trouve le curseur, généralement après des
10
11 opérations de lecture ou d'écriture.
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

03 {
1
2
3
4
5
Navigation Dans Un Fichier : [‘Tell()’]
6
7
8
9
10
11
12
13
14
}
Programming Language : PYTHON
Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

1
2
3 00 {
4
5
6

Exercice
7
8
9
10
11

}
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

1
2
3
Créez un fichier texte vide appelé ‘lp.txt’.
4
5 Ouvrez le fichier en mode écriture et écrivez une ligne de texte de votre choix.
6 Fermez le fichier (il est possible d’utiliser ‘with’).
7 Réouvrez le fichier en mode lecture et lisez le contenu.
8 Affichez le nom du fichier, le mode d'ouverture, et l'encodage utilisé.
9
déplacer le curseur au début du fichier.
10
11 Réouvrez le fichier en mode lecture et lisez les 10 premiers caractères.
12 afficher la position actuelle du curseur.
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

1
2
3 04 {
4
5
6
7 Les bibliothèques :
8
9
10 [‘os’,‘shutil’]
11

}
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

04 {
1
2
3

Définition “Os” :
4
5
6
7 La bibliothèque os fournit une interface pour
8 interagir avec le système d'exploitation. Elle
9 permet d'effectuer des opérations liées au système
10 de fichiers, au répertoire en cours, etc.
11
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

04 {
1
2
3
4 Les fonctions plus connus : [‘os’]
5
6 os.getcwd() #Obtient le répertoire de travail actuel.
7
8 os.listdir(path) #Liste les fichiers et les répertoires
9 dans le chemin spécifié.
10 os.path.exists(path) #Vérifie si le chemin spécifié
11 existe.
12
13 os.path.join(path1, path2, ...) #Joindre plusieurs
parties de chemins pour former un chemin complet.
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

04 {
1
2
3
4 Exemple fonctions plus connus : [‘os’]
5
6 current_directory = os.getcwd()
7
8 files_in_directory = os.listdir('/chemin/vers/le/repertoire')
9
10 if os.path.exists('/chemin/vers/le/fichier.txt'):
11 print("Le fichier existe.")
12
full_path = os.path.join('/dossier/parent', 'sous-dossier', 'fichier.txt')
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

04 {
1
2
3
4 Exemple d'utilisation de [‘os’]
5 import os
6
7 # Obtenir le répertoire de travail actuel
8
9 current_directory = os.getcwd()
10 print(f"Répertoire de travail actuel : {current_directory}")
11
# Listage des fichiers dans un répertoire
12
13 files_in_directory = os.listdir(current_directory)
14 print(f"Fichiers dans le répertoire : {files_in_directory}")

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

04 {
1
2
3

Définition “shutil” :
4
5
6
7 La bibliothèque shutil offre des opérations de haut
8 niveau pour manipuler des fichiers et des
9 répertoires. Elle est construite au-dessus de os et
10 propose des fonctionnalités supplémentaires.
11
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

04 {
1
2
3
4 Les fonctions plus connus : [‘shutil’]
5
6 shutil.copy(src, dst) #Copie un fichier de la source (src) vers la destination (dst).
7
8 shutil.copytree(src, dst) #Copie un répertoire entier de la source (src) vers la
9 destination (dst).
10 shutil.rmtree(path) #Supprime un répertoire et son contenu de manière récursive.
11
12 shutil.move(src, dst) #Déplace un fichier ou un répertoire de la source (src)
13 vers la destination (dst).
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

04 {
1
2
3
4 Exemple fonctions plus connus : [‘shutil’]
5
6 shutil.copy('source.txt', 'destination.txt')
7
8 shutil.copytree('source_folder', 'destination_folder')
9
10 shutil.move('ancien_emplacement/fichier.txt', 'nouvel_emplacement/')
11
12 shutil.rmtree('/chemin/vers/le/repertoire_a_supprimer')
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

04 {
1
2
3
4 Exemple d'utilisation de [‘shutil’]
5
import shutil
6
7 # Copier un fichier
8 shutil.copy('source.txt', 'destination.txt')
9 print("Fichier copié avec succès.")
10
11 # Copier un répertoire récursivement
12 shutil.copytree('source_folder', 'destination_folder')
13 print("Répertoire copié avec succès.")
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

04 {
1
2
3
4 Exercice d'application
5
6 Objectif : Créer une fonction qui copie tous les
7 fichiers d'un certain type (par exemple, '.txt')
8 d'un répertoire source vers un répertoire de
9 destination.
10
11
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

04 {
1
2
3
4
5
6
7
8
9
10
11
12
13
14

Programming Language : PYTHON


Intro.py Operations.py File_Object.. File_naviga.. Libraries.py

1
2
3
Programming ‘Python’ {
4
5
6 ‘Text’ : [
7 " Thanks for your attention"
8
]
9
10
11
12
13 }
14

Programming Language : PYTHON

Vous aimerez peut-être aussi