Update
This commit is contained in:
@@ -38,7 +38,23 @@ Parcourrir un fichier ligne par ligne:
|
||||
>>> 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)}]")
|
||||
```
|
||||
|
||||
|
||||
@@ -56,8 +72,8 @@ fichier.close()
|
||||
##### Type d'ouverture:
|
||||
|
||||
```python
|
||||
r, pour une ouverture en lecture (READ).
|
||||
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.
|
||||
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.
|
||||
@@ -92,7 +108,7 @@ if os.path.exists("empty_folder"):
|
||||
|
||||
|
||||
|
||||
#### Chemins
|
||||
#### Chemins (os.path)
|
||||
|
||||
##### Méthodes:
|
||||
|
||||
@@ -206,3 +222,37 @@ 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
|
||||
```
|
||||
|
||||
|
||||
Reference in New Issue
Block a user