Outils pour utilisateurs

Outils du site


prog:fichiers

Ceci est une ancienne révision du document !


Les fichiers en Python

Fichiers texte

# Lecture d'un fichier ligne par ligne
chemin = "Testfile.txt"
with open(chemin, "r", encoding='utf-8') as f:
    lignes = f.readlines() # Conserve les \n
    # lignes = f.read().splitlines() # Ne conserve pas les \n
    print (lignes)
    # f.seek(0) repositionne le pointeur en position 0 du fichier
 
# Pareil mais avec une boucle ligne par ligne
chemin = "Testfile.txt"
with open(chemin, "r", encoding='utf-8') as f:
   for ligne in f:
    print (ligne)
 
# Ecriture dans un fichier
chemin = "Testfile.txt"
# Mode "w" write : écrase le fichier, "a" append : écrit à la suite
with open(chemin, "a", encoding='utf-8') as f:
    f.write("\nRéussi")
 
# Autre possibilité : utiliser open comme une fonction
chemin = "Testfile.txt"
f = open(chemin, "r") # Ici on peut utiliser aussi "w" et "a"
f.close() # Indispensable si on utilise open comme une fonction

Fichiers Json

<code python> # Fichier json import json chemin = “/Users/jbpuel/Nextcloud/Programmation/Python/Testfile.json” with open(chemin, “w”, encoding='utf-8') as f:

  json.dump("Chaîne pêche", f)
  #json.dump(list(range(10)), f, indent=4)

<code>

prog/fichiers.1584613646.txt.gz · Dernière modification : 2020/03/19 10:27 de jbpuel