Lire et écrire des fichiers

Python peut lire et écrire des fichiers, via la commande open().

On se limitera aux fichiers-texte, bien que Python supporte le format binaire.

[1]:
# Ouverture du fichier
fichier = open('open-files_exo1.txt', 'r')

# Extraction des données d'un seul bloc
data = fichier.read()

# Fermeture du fichier
fichier.close()

# Et maintenant, tous ensemble :
print(data)
Young man, there's no need to feel down.
I said, young man, pick yourself off the ground.
I said, young man, 'cause you're in a new town
There's no need to be unhappy.

Young man, there's a place you can go.
I said, young man, when you're short on your dough.
You can stay there, and I'm sure you will find
Many ways to have a good time.

It's fun to stay at the y-m-c-a.
It's fun to stay at the y-m-c-a.

Note : On préférera l’utilisation du context manager with.

[2]:
# Le fichier est ouvert automatiquement à l'entrée du with

with open('open-files_exo1.txt', 'r') as fichier:
    data = fichier.readlines()  # Extraction des données en lignes
    print('fichier est fermé (dans le with) ?', fichier.closed)

# Le fichier est fermé automatiquement à la sortie du with
print('fichier est fermé ?', fichier.closed)

data
fichier est fermé (dans le with) ? False
fichier est fermé ? True
[2]:
["Young man, there's no need to feel down. \n",
 'I said, young man, pick yourself off the ground. \n',
 "I said, young man, 'cause you're in a new town \n",
 "There's no need to be unhappy. \n",
 '\n',
 "Young man, there's a place you can go. \n",
 "I said, young man, when you're short on your dough. \n",
 "You can stay there, and I'm sure you will find \n",
 'Many ways to have a good time. \n',
 '\n',
 "It's fun to stay at the y-m-c-a. \n",
 "It's fun to stay at the y-m-c-a. \n"]
[3]:
# Le mode 'w' donne le mode en écriture
with open('open-files_exo1_copie.txt','w') as fichier :
    fichier.writelines(data)

# Append, 'a', permet de compléter le fichier sans le remplacer
with open('open-files_exo1_copie.txt','a') as fichier :
    fichier.writelines(data)
[4]:
# `fichier` est itérable, chaque itération renvoie une ligne du fichier

with open('open-files_exo1.txt') as fichier :
    for ligne in fichier:
        print('**', ligne, end='')  # <- end='' évite l'ajout d'un saut de ligne supplémentaire
** Young man, there's no need to feel down.
** I said, young man, pick yourself off the ground.
** I said, young man, 'cause you're in a new town
** There's no need to be unhappy.
**
** Young man, there's a place you can go.
** I said, young man, when you're short on your dough.
** You can stay there, and I'm sure you will find
** Many ways to have a good time.
**
** It's fun to stay at the y-m-c-a.
** It's fun to stay at the y-m-c-a.
[5]:
# attention !
# `ligne` contient le symbole de fin de ligne

repr(ligne)
[5]:
'"It\'s fun to stay at the y-m-c-a. \\n"'

Exercices