{ "cells": [ { "cell_type": "markdown", "metadata": { "nbsphinx": "hidden" }, "source": [ "[prev: Bien boucler en Python](loop-pythonic.ipynb) | [home](../index.ipynb) | [next: Aperçu des fonctions *built-in*](builtin-functions.ipynb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Lire et écrire des fichiers\n", "\n", "Python peut lire et écrire des fichiers, *via* la commande `open()`.\n", "\n", "On se limitera aux fichiers-texte, bien que Python supporte le format binaire." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "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", "\n" ] } ], "source": [ "# Ouverture du fichier\n", "fichier = open('open-files_exo1.txt', 'r')\n", "\n", "# Extraction des données d'un seul bloc\n", "data = fichier.read()\n", "\n", "# Fermeture du fichier\n", "fichier.close()\n", "\n", "# Et maintenant, tous ensemble :\n", "print(data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Note :** On préférera l'utilisation du *context manager* `with`." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "fichier est fermé (dans le with) ? False\n", "fichier est fermé ? True\n" ] }, { "data": { "text/plain": [ "[\"Young man, there's no need to feel down. \\n\",\n", " 'I said, young man, pick yourself off the ground. \\n',\n", " \"I said, young man, 'cause you're in a new town \\n\",\n", " \"There's no need to be unhappy. \\n\",\n", " '\\n',\n", " \"Young man, there's a place you can go. \\n\",\n", " \"I said, young man, when you're short on your dough. \\n\",\n", " \"You can stay there, and I'm sure you will find \\n\",\n", " 'Many ways to have a good time. \\n',\n", " '\\n',\n", " \"It's fun to stay at the y-m-c-a. \\n\",\n", " \"It's fun to stay at the y-m-c-a. \\n\"]" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Le fichier est ouvert automatiquement à l'entrée du with\n", "\n", "with open('open-files_exo1.txt', 'r') as fichier:\n", " data = fichier.readlines() # Extraction des données en lignes\n", " print('fichier est fermé (dans le with) ?', fichier.closed)\n", "\n", "# Le fichier est fermé automatiquement à la sortie du with\n", "print('fichier est fermé ?', fichier.closed)\n", "\n", "data" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "# Le mode 'w' donne le mode en écriture\n", "with open('open-files_exo1_copie.txt','w') as fichier :\n", " fichier.writelines(data)\n", "\n", "# Append, 'a', permet de compléter le fichier sans le remplacer\n", "with open('open-files_exo1_copie.txt','a') as fichier :\n", " fichier.writelines(data)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "** 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" ] } ], "source": [ "# `fichier` est itérable, chaque itération renvoie une ligne du fichier\n", "\n", "with open('open-files_exo1.txt') as fichier :\n", " for ligne in fichier:\n", " print('**', ligne, end='') # <- end='' évite l'ajout d'un saut de ligne supplémentaire" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'\"It\\'s fun to stay at the y-m-c-a. \\\\n\"'" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# attention !\n", "# `ligne` contient le symbole de fin de ligne\n", "\n", "repr(ligne)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercices" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- [Statistiques d'un échantillon](../exercises/exercises.ipynb#Exercice-7-:-statistiques-d'un-échantillon)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.12" } }, "nbformat": 4, "nbformat_minor": 4 }