{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# [File I/O](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files)\n", "Reading and writing files." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Working with paths" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "\n", "current_file = os.path.realpath('file_io.ipynb') \n", "print('current file: {}'.format(current_file))\n", "# Note: in .py files you can get the path of current file by __file__\n", "\n", "current_dir = os.path.dirname(current_file) \n", "print('current directory: {}'.format(current_dir))\n", "# Note: in .py files you can get the dir of current file by os.path.dirname(__file__)\n", "\n", "data_dir = os.path.join(current_dir, 'data')\n", "print('data directory: {}'.format(data_dir))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Checking if path exists" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print('exists: {}'.format(os.path.exists(data_dir)))\n", "print('is file: {}'.format(os.path.isfile(data_dir)))\n", "print('is directory: {}'.format(os.path.isdir(data_dir)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Reading files" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "file_path = os.path.join(data_dir, 'simple_file.txt')\n", "\n", "with open(file_path, 'r') as simple_file:\n", " for line in simple_file:\n", " print(line.strip())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The [`with`](https://docs.python.org/3/reference/compound_stmts.html#the-with-statement) statement is for obtaining a [context manager](https://docs.python.org/3/reference/datamodel.html#with-statement-context-managers) that will be used as an execution context for the commands inside the `with`. Context managers guarantee that certain operations are done when exiting the context. \n", "\n", "In this case, the context manager guarantees that `simple_file.close()` is implicitly called when exiting the context. This is a way to make developers life easier: you don't have to remember to explicitly close the file you openened nor be worried about an exception occuring while the file is open. Unclosed file maybe a source of a resource leak. Thus, prefer using `with open()` structure always with file I/O.\n", "\n", "To have an example, the same as above without the `with`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "file_path = os.path.join(data_dir, 'simple_file.txt')\n", "\n", "# THIS IS NOT THE PREFERRED WAY\n", "simple_file = open(file_path, 'r')\n", "for line in simple_file:\n", " print(line.strip())\n", "simple_file.close() # This has to be called explicitly " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Writing files" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "new_file_path = os.path.join(data_dir, 'new_file.txt')\n", "\n", "with open(new_file_path, 'w') as my_file:\n", " my_file.write('This is my first file that I wrote with Python.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now go and check that there is a new_file.txt in the data directory. After that you can delete the file by:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "if os.path.exists(new_file_path): # make sure it's there\n", " os.remove(new_file_path)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.5.4" } }, "nbformat": 4, "nbformat_minor": 2 }