259 lines
6.5 KiB
Markdown
259 lines
6.5 KiB
Markdown
# Fichiers
|
|
|
|
|
|
|
|
#### Fonction open:
|
|
|
|
##### Ouvrir un fichier:
|
|
|
|
```python
|
|
fichier = open("test.py","r")
|
|
print(fichier)
|
|
fichier.close()
|
|
|
|
>>> <_io.TextIOWrapper name='test.py' mode='r' encoding='UTF-8'>
|
|
```
|
|
|
|
|
|
|
|
##### Ouvrir et afficher un fichier:
|
|
|
|
```python
|
|
fichier = open("test.py","r")
|
|
print(fichier.read())
|
|
fichier.close()
|
|
```
|
|
|
|
Autre syntaxe:
|
|
|
|
```python
|
|
with open("test.py","r") as fichier:
|
|
print(fichier.read())
|
|
```
|
|
|
|
Parcourrir un fichier ligne par ligne:
|
|
|
|
```python
|
|
>>> fichier = open("serve.py","r")
|
|
>>> for x in fichier:
|
|
... print(x)
|
|
...
|
|
```
|
|
|
|
```python
|
|
>>> with open("pecl-help.txt") as fichier:
|
|
... for line in fichier:
|
|
... print(line, end='')
|
|
...
|
|
```
|
|
|
|
Ouverture d'un fichier binaire:
|
|
|
|
```python
|
|
>>> with open('file', 'rb') as fichierbinaire:
|
|
... octets = fichierbinaire.read() # le fichier est lu en entier
|
|
... print("on a lu un objet de type", type(octets))
|
|
... for i, octet in enumerate(octets):
|
|
... print(f"{i} → {repr(chr(octet))} [{hex(octet)}]")
|
|
```
|
|
|
|
|
|
|
|
##### Ecrire dans un fichier (à la suite, sur une nouvelle ligne):
|
|
|
|
```python
|
|
fichier = open("test.py","a")
|
|
fichier.write("\n\n\"\"\" Commentaire \"\"\"")
|
|
fichier.close()
|
|
```
|
|
|
|
|
|
|
|
##### Type d'ouverture:
|
|
|
|
```python
|
|
r, pour une ouverture en lecture (READ). (Par défaut)
|
|
w, pour une ouverture en écriture (WRITE), à chaque ouverture le contenu du fichier est écrasé. Si le fichier n'existe pas, Python le crée.
|
|
a, pour une ouverture en mode ajout à la fin du fichier (APPEND). Si le fichier n'existe pas python le crée.
|
|
b, pour une ouverture en mode binaire.
|
|
t, pour une ouverture en mode texte.
|
|
x, crée un nouveau fichier et l'ouvre pour écriture
|
|
```
|
|
|
|
##### Test si un fichier existe:
|
|
|
|
```python
|
|
import os
|
|
if os.path.exists("serve.py"):
|
|
print("Le fichier existe")
|
|
else:
|
|
print("Le fichier n'existe pas")
|
|
```
|
|
|
|
##### Supprimer un fichier:
|
|
|
|
```python
|
|
import os
|
|
if os.path.exists("zz.py"):
|
|
os.remove("zz.py")
|
|
```
|
|
|
|
##### Supprimer un dossier:
|
|
|
|
```python
|
|
import os
|
|
if os.path.exists("empty_folder"):
|
|
os.rmdir("empty_folder")
|
|
```
|
|
|
|
|
|
|
|
#### Chemins (os.path)
|
|
|
|
##### Méthodes:
|
|
|
|
```
|
|
>>> help(os.path)
|
|
|
|
abspath(path) → Retourne un chemin absolu
|
|
basename(p) → Retourne le dernier élément d'un chemin
|
|
commonprefix(list) → Retourne le chemin commun le plus long d'une liste de chemins
|
|
dirname(p) → Retourne le dossier parent de l'élément
|
|
exists(path) → Test si un chemin existe
|
|
getaTime(filename) → Retourne la date du dernier accès au fichier [os.stat()]
|
|
getctime(filename) → Retourne la date du dernier changement de metadonnées du fichier
|
|
getmTime(filename) → Retourne la date de la dernière modification du fichier
|
|
getsize(filename) → Retourne la tailkle d'un fichier (en octets)
|
|
isabs(s) → Test si un chemin est absolu
|
|
isdir(s) → Test si le chemin est un dossier
|
|
isfile(path) → Test si le chemin est un fichier régulier
|
|
islink(path) → Test si le chemin est un lien symbolique
|
|
ismount(path) → Test si le chemin est un point de montage
|
|
join(path, s) → Ajoute un élément au chemin passé en paramètre
|
|
normcase(s) → Normalise la casse d'un chemin
|
|
normpath(path) → Normalise le chemin, élimine les doubles barres obliques, etc.
|
|
realpath(filename) → Retourne le chemin canonique du nom de fichier spécifié (élimine les liens symboliques)
|
|
samefile(f1, f2) → Test si deux chemins font référence au même fichier réel
|
|
sameopenfile(f1, f2) → Test si deux objets de fichiers ouverts font référence au même fichier
|
|
split(p) → Fractionne un chemin d'accès. Retourne un tuple
|
|
```
|
|
|
|
##### Exemples:
|
|
|
|
```python
|
|
>>> import os.path
|
|
>>> help(os.path)
|
|
|
|
>>> path = "/Users/bruno/PycharmProjects/webserver/index.py"
|
|
|
|
>>> os.path.dirname(path)
|
|
'/Users/bruno/PycharmProjects/webserver'
|
|
>>> os.path.basename(path)
|
|
'index.py'
|
|
>>> os.path.split(path)
|
|
('/Users/bruno/PycharmProjects/webserver', 'index.py')
|
|
>>> os.path.abspath(".")
|
|
'/Users/bruno'
|
|
```
|
|
|
|
```python
|
|
>>> os.listdir(os.path.dirname(path))
|
|
['functions.py', 'server.py', 'index.py', 'serve.py', '__pycache__', 'test.py', 'open.py', '.idea']
|
|
```
|
|
|
|
```python
|
|
# lister récursivement tous les fichiers
|
|
|
|
>>> import os
|
|
>>> folder = '/Users/bruno/PycharmProjects'
|
|
>>> for path, dirs, files in os.walk(folder):
|
|
... for filename in files:
|
|
... print(filename)
|
|
...
|
|
.DS_Store
|
|
pyvenv.cfg
|
|
pip3.7
|
|
python3
|
|
easy_install
|
|
python
|
|
.../...
|
|
```
|
|
|
|
##### Connaître le répertoire courante:
|
|
|
|
```python
|
|
>>> import os
|
|
>>> os.getcwd()
|
|
'/Users/bruno/PycharmProjects/webserver'
|
|
```
|
|
|
|
|
|
|
|
##### Rechercher des éléments par motif
|
|
|
|
```
|
|
* → n'importe quel séquence de caractères
|
|
? → n'importe quel caractère
|
|
[] → n'importe quel caractère listé entre les crochets
|
|
```
|
|
|
|
```python
|
|
>>> import glob
|
|
|
|
# Methodes:
|
|
glob.glob(motif) → Liste les dossiers et les fichiers correspondants au motif
|
|
glob.iglob(motif) → Idem que glob mais retourne un itérateur
|
|
|
|
# Recherche des fichiers python:
|
|
>>> glob.glob("/Users/bruno/PycharmProjects/webserver/*.py")
|
|
['/Users/bruno/PycharmProjects/webserver/functions.py', '/Users/bruno/PycharmProjects/webserver/server.py', '/Users/bruno/PycharmProjects/webserver/index.py', '/Users/bruno/PycharmProjects/webserver/serve.py', '/Users/bruno/PycharmProjects/webserver/test.py', '/Users/bruno/PycharmProjects/webserver/open.py']
|
|
```
|
|
|
|
|
|
|
|
##### Manipuler les éléments
|
|
|
|
```python
|
|
os.makedirs(path) → Créer récursivement tous les dossiers d'un path si ceux-ci n'existent pas
|
|
os.mkdir(path) → Créer le dernier dossier d'un path. Si un des dossiers n'existe pas une erreur est retournée
|
|
os.remove(path) → Supprime le fichier / dossier indiqué
|
|
os.rename(old, new) → Renomme le fichier / dossier indiqué
|
|
```
|
|
|
|
|
|
|
|
#### pathlib
|
|
|
|
Depuis Python 3.4, le module `os.path` est obsolète et est remplacé par la librairie `pathlib`.
|
|
|
|
```python
|
|
from pathlib import Path
|
|
|
|
help(pathlib)
|
|
```
|
|
|
|
```python
|
|
from pathlib import Path
|
|
filename = 'scratch.py'
|
|
path = Path(filename)
|
|
|
|
if path.exists():
|
|
print("existe")
|
|
print(path.stat().st_size) # taille
|
|
print(path.stat().st_mtime) # dernière modif
|
|
|
|
try:
|
|
path.unlink()
|
|
except FileNotFoundError:
|
|
print("Pas de fichier à supprimer")
|
|
```
|
|
|
|
```python
|
|
from pathlib import Path
|
|
dirpath = Path('.') # répertoire courant
|
|
|
|
for py in dirpath.glob("*.py"):
|
|
print(py) # liste des fichiers Python du répertoire courant
|
|
```
|
|
|