{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "All the IPython Notebooks in this lecture series by Dr. Milan Parmar are available @ **[GitHub](https://github.com/milaan9/05_Python_Files)**\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python File I/O\n", "\n", "In this class, you'll learn about Python file operations. More specifically, opening a file, reading from it, writing into it, closing it, and various file methods that you should be aware of." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Files\n", "\n", "Files are named locations on disk to store related information. They are used to permanently store data in a non-volatile memory (e.g. hard disk).\n", "\n", "Since Random Access Memory (RAM) is volatile (which loses its data when the computer is turned off), we use files for future use of the data by permanently storing them.\n", "\n", "When we want to read from or write to a file, we need to open it first. When we are done, it needs to be closed so that the resources that are tied with the file are freed.\n", "\n", "Hence, in Python, a file operation takes place in the following order:\n", "\n", "1. Open a file\n", "2. Close the file\n", "3. Read or write (perform operation)\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Opening Files in Python\n", "\n", "Python has a built-in **`open()`** function to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly.\n", "\n", "```python\n", ">>> f = open(\"test.txt\") # open file in current directory\n", ">>> f = open(\"C:/Python99/README.txt\") # specifying full path\n", "```\n", "\n", "We can specify the mode while opening a file. In mode, we specify whether we want to read **`r`**, write **`w`** or append **`a`** to the file. We can also specify if we want to open the file in text mode or binary mode.\n", "\n", "The default is reading in text mode. In this mode, we get strings when reading from the file.\n", "\n", "On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-text files like images or executable files.\n", "\n", "| Mode | Description |\n", "|:----:| :--- |\n", "| **`r`** | Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode. | \n", "| **`t`** | Opens in text mode. (default). | \n", "| **`b`** | Opens in binary mode. | \n", "| **`x`** | Opens a file for exclusive creation. If the file already exists, the operation fails. | \n", "| **`rb`** | Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode. | \n", "| **`r+`** | Opens a file for both reading and writing. The file pointer placed at the beginning of the file. | \n", "| **`rb+`** | Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file. | \n", "| **`w`** | Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. | \n", "| **`wb`** | Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. | \n", "| **`w+`** | Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. | \n", "| **`wb+`** | Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. | \n", "| **`a`** | Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. | \n", "| **`ab`** | Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. | \n", "| **`a+`** | Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. |\n", "| **`ab+`** | Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. | " ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:33:59.892237Z", "start_time": "2021-06-18T15:33:59.884426Z" } }, "outputs": [], "source": [ "f = open(\"test.txt\") # equivalent to 'r' or 'rt'" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:00.640278Z", "start_time": "2021-06-18T15:34:00.635397Z" } }, "outputs": [], "source": [ "f = open(\"test.txt\",'w') # write in text mode" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:01.153947Z", "start_time": "2021-06-18T15:34:01.134419Z" } }, "outputs": [], "source": [ "f = open(\"logo.png\",'r+b') # read and write in binary mode" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Unlike other languages, the character **`a`** does not imply the number 97 until it is encoded using **`ASCII`** (or other equivalent encodings).\n", "\n", "Moreover, the default encoding is platform dependent. In windows, it is **`cp1252`** but **`utf-8`** in Linux.\n", "\n", "So, we must not also rely on the default encoding or else our code will behave differently in different platforms.\n", "\n", "Hence, when working with files in text mode, it is highly recommended to specify the encoding type." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:05.598733Z", "start_time": "2021-06-18T15:34:05.587019Z" } }, "outputs": [], "source": [ "f = open(\"test.txt\", mode='r', encoding='utf-8')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Closing Files in Python\n", "\n", "When we are done with performing operations on the file, we need to properly close the file.\n", "\n", "Closing a file will free up the resources that were tied with the file. It is done using the **`close()`** method available in Python.\n", "\n", "Python has a garbage collector to clean up unreferenced objects but we must not rely on it to close the file." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:06.985930Z", "start_time": "2021-06-18T15:34:06.979096Z" } }, "outputs": [], "source": [ "f = open(\"test.txt\", encoding = 'utf-8')\n", "# perform file operations\n", "f.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This method is not entirely safe. If an exception occurs when we are performing some operation with the file, the code exits without closing the file.\n", "\n", "A safer way is to use a **[try-finally](https://github.com/milaan9/05_Python_Files/blob/main/004_Python_Exceptions_Handling.ipynb)** block." ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:08.405351Z", "start_time": "2021-06-18T15:34:08.387777Z" } }, "outputs": [], "source": [ "try:\n", " f = open(\"test.txt\", encoding = 'utf-8')\n", " # perform file operations\n", "finally:\n", " f.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This way, we are guaranteeing that the file is properly closed even if an exception is raised that causes program flow to stop.\n", "\n", "The best way to close a file is by using the **`with`** statement. This ensures that the file is closed when the block inside the **`with`** statement is exited.\n", "\n", "We don't need to explicitly call the **`close()`** method. It is done internally.\n", "\n", "```python\n", ">>>with open(\"test.txt\", encoding = 'utf-8') as f:\n", " # perform file operations\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The file Object Attributes\n", "\n", "* **file.closed** - Returns true if file is closed, false otherwise.\n", "* **file.mode** - Returns access mode with which file was opened.\n", "* **file.name** - Returns name of the file." ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:11.108946Z", "start_time": "2021-06-18T15:34:11.098205Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Name of the file: data.txt\n", "Closed or not : False\n", "Opening mode : wb\n" ] } ], "source": [ "# Open a file\n", "data = open(\"data.txt\", \"wb\")\n", "print (\"Name of the file: \", data.name)\n", "print (\"Closed or not : \", data.closed)\n", "print (\"Opening mode : \", data.mode)\n", "data.close() #closed data.txt file" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Writing to Files in Python\n", "\n", "In order to write into a file in Python, we need to open it in write **`w`**, append **`a`** or exclusive creation **`x`** mode.\n", "\n", "We need to be careful with the **`w`** mode, as it will overwrite into the file if it already exists. Due to this, all the previous data are erased.\n", "\n", "Writing a string or sequence of bytes (for binary files) is done using the **`write()`** method. This method returns the number of characters written to the file." ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:17.998538Z", "start_time": "2021-06-18T15:34:17.979009Z" } }, "outputs": [], "source": [ "with open(\"test_1.txt\",'w',encoding = 'utf-8') as f:\n", " f.write(\"my first file\\n\")\n", " f.write(\"This file\\n\\n\")\n", " f.write(\"contains three lines\\n\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This program will create a new file named **`test_1.txt`** in the current directory if it does not exist. If it does exist, it is overwritten.\n", "\n", "We must include the newline characters ourselves to distinguish the different lines." ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:21.520483Z", "start_time": "2021-06-18T15:34:21.515603Z" } }, "outputs": [], "source": [ "with open(\"test_2.txt\",'w',encoding = 'utf-8') as f:\n", " f.write(\"This is file\\n\")\n", " f.write(\"my\\n\")\n", " f.write(\"first file\\n\")" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:22.612276Z", "start_time": "2021-06-18T15:34:22.595674Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "done\n" ] } ], "source": [ "# open a file in current directory\n", "data = open(\"data_1.txt\", \"w\") # \"w\" write in text mode,\n", "data.write(\"Welcome to Dr. Milan Parmar's Python Tutorial\")\n", "print(\"done\")\n", "data.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. Reading Files in Python\n", "\n", "To read a file in Python, we must open the file in reading **`r`** mode.\n", "\n", "There are various methods available for this purpose. We can use the **`read(size)`** method to read in the **`size`** number of data. If the **`size`** parameter is not specified, it reads and returns up to the end of the file.\n", "\n", "We can read the **`text_1.txt`** file we wrote in the above section in the following way:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:37.419777Z", "start_time": "2021-06-18T15:34:37.397313Z" } }, "outputs": [ { "data": { "text/plain": [ "'my first'" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f = open(\"test_1.txt\",'r',encoding = 'utf-8')\n", "f.read(8) # read the first 8 data characters" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:38.371914Z", "start_time": "2021-06-18T15:34:38.364105Z" } }, "outputs": [ { "data": { "text/plain": [ "' file'" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.read(5) # read the next 5 data characters" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:38.853355Z", "start_time": "2021-06-18T15:34:38.837734Z" } }, "outputs": [ { "data": { "text/plain": [ "'\\nThis file\\n\\ncontains three lines\\n'" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.read() # read in the rest till end of file" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:39.275232Z", "start_time": "2021-06-18T15:34:39.261561Z" } }, "outputs": [ { "data": { "text/plain": [ "''" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.read() # further reading returns empty sting" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can see that the **`read()`** method returns a newline as **`'\\n'`**. Once the end of the file is reached, we get an empty string on further reading.\n", "\n", "We can change our current file cursor (position) using the **`seek()`** method. Similarly, the **`tell()`** method returns our current position (in number of bytes)." ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:39.977372Z", "start_time": "2021-06-18T15:34:39.965655Z" } }, "outputs": [ { "data": { "text/plain": [ "50" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.tell() # get the current file position" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:40.257643Z", "start_time": "2021-06-18T15:34:40.239090Z" } }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.seek(0) # bring file cursor to initial position" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:40.645334Z", "start_time": "2021-06-18T15:34:40.639476Z" }, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "my first file\n", "This file\n", "\n", "contains three lines\n", "\n" ] } ], "source": [ "print(f.read()) # read the entire file" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can read a file line-by-line using a **[for loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/005_Python_for_Loop.ipynb)**. This is both efficient and fast." ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:44.541300Z", "start_time": "2021-06-18T15:34:44.532516Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "my first file\n", "This file\n", "\n", "contains three lines\n" ] } ], "source": [ "f = open(\"test_1.txt\",'r',encoding = 'utf-8')\n", "for line in f:\n", " print(line, end = '')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this program, the lines in the file itself include a newline character **`\\n`**. So, we use the end parameter of the **`print()`** function to avoid two newlines when printing." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Alternatively, we can use the **`readline()`** method to read individual lines of a file. This method reads a file till the newline, including the newline character." ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:46.631127Z", "start_time": "2021-06-18T15:34:46.611600Z" } }, "outputs": [ { "data": { "text/plain": [ "'my first file\\n'" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.seek(0) # bring file cursor to initial position\n", "f.readline()" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:47.098896Z", "start_time": "2021-06-18T15:34:47.078394Z" } }, "outputs": [ { "data": { "text/plain": [ "'This file\\n'" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.readline()" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:47.597430Z", "start_time": "2021-06-18T15:34:47.579852Z" } }, "outputs": [ { "data": { "text/plain": [ "'\\n'" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.readline()" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:49.810301Z", "start_time": "2021-06-18T15:34:49.796633Z" } }, "outputs": [ { "data": { "text/plain": [ "'contains three lines\\n'" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.readline()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Lastly, the **`readlines()`** method returns a list of remaining lines of the entire file. All these reading methods return empty values when the end of file **(EOF)** is reached." ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:52.456765Z", "start_time": "2021-06-18T15:34:52.437237Z" }, "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "['my first file\\n', 'This file\\n', '\\n', 'contains three lines\\n']" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.seek(0) # bring file cursor to initial position\n", "f.readlines()" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:34:54.966025Z", "start_time": "2021-06-18T15:34:54.956260Z" }, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Welcome to Dr. Milan Parmar\n", "'s Python Tutorial\n" ] } ], "source": [ "# Open a file\n", "data = open(\"data_1.txt\", \"r+\")\n", "file_data = data.read(27) # read 3.375 byte only\n", "full_data = data.read() # read all byte into file from last cursor\n", "print(file_data)\n", "print(full_data)\n", "data.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## File Positions\n", "\n", "The **`tell()`** method tells you the current position within the file; in other words, the next read or write will occur at that many bytes from the beginning of the file.\n", "\n", "The **`seek(offset[, from])`** method changes the current file position. The offset argument indicates the number of bytes to be moved. The from argument specifies the reference position from where the bytes are to be moved.\n", "\n", "If from is set to 0, the beginning of the file is used as the reference position. If it is set to 1, the current position is used as the reference position. If it is set to 2 then the end of the file would be taken as the reference position." ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:35:02.590964Z", "start_time": "2021-06-18T15:35:02.572412Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "current position after reading 27 byte : 27\n", "Welcome to Dr. Milan Parmar\n", "Welcome to Dr. Milan Parmar's Python Tutorial\n", "position after reading file : 45\n" ] } ], "source": [ "# Open a file\n", "data = open(\"data_1.txt\", \"r+\")\n", "file_data = data.read(27) # read 18 byte only\n", "print(\"current position after reading 27 byte :\",data.tell())\n", "data.seek(0) #here current position set to 0 (starting of file)\n", "full_data = data.read() #read all byte\n", "print(file_data)\n", "print(full_data)\n", "print(\"position after reading file : \",data.tell())\n", "data.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Python File Methods\n", "\n", "There are various methods available with the file object. Some of them have been used in the above examples.\n", "\n", "Here is the complete list of methods in text mode with a brief description:\n", "\n", "| Method | Description |\n", "|:----| :--- |\n", "| **`close()`** | Closes an opened file. It has no effect if the file is already closed. | \n", "| **`detach()`** | Separates the underlying binary buffer from the **`TextIOBase`** and returns it. | \n", "| **`fileno()`** | Returns an integer number (file descriptor) of the file. | \n", "| **`flush()`** | Flushes the write buffer of the file stream. | \n", "| **`isatty()`** | Returns **`True`** if the file stream is interactive. | \n", "| **`read(n)`** | Reads at most `n` characters from the file. Reads till end of file if it is negative or `None`. | \n", "| **`readable()`** | Returns **`True`** if the file stream can be read from. | \n", "| **`readline(n=-1)`** | Reads and returns one line from the file. Reads in at most **`n`** bytes if specified. | \n", "| **`readlines(n=-1)`** | Reads and returns a list of lines from the file. Reads in at most **`n`** bytes/characters if specified. | \n", "| **`seek(offset,from=SEEK_SET)`** | Changes the file position to **`offset`** bytes, in reference to `from` (start, current, end). | \n", "| **`seekable()`** | Returns **`True`** if the file stream supports random access. | \n", "| **`tell()`** | Returns the current file location. | \n", "| **`truncate(size=None)`** | Resizes the file stream to **`size`** bytes. If **`size`** is not specified, resizes to current location.. | \n", "| **`writable()`** | Returns **`True`** if the file stream can be written to. | \n", "| **`write(s)`** | Writes the string **`s`** to the file and returns the number of characters written.. | \n", "| **`writelines(lines)`** | Writes a list of **`lines`** to the file.. | " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "hide_input": false, "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.8.8" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": { "height": "calc(100% - 180px)", "left": "10px", "top": "150px", "width": "204.797px" }, "toc_section_display": true, "toc_window_display": false }, "varInspector": { "cols": { "lenName": 16, "lenType": 16, "lenVar": 40 }, "kernels_config": { "python": { "delete_cmd_postfix": "", "delete_cmd_prefix": "del ", "library": "var_list.py", "varRefreshCmd": "print(var_dic_list())" }, "r": { "delete_cmd_postfix": ") ", "delete_cmd_prefix": "rm(", "library": "var_list.r", "varRefreshCmd": "cat(var_dic_list()) " } }, "types_to_exclude": [ "module", "function", "builtin_function_or_method", "instance", "_Feature" ], "window_display": false } }, "nbformat": 4, "nbformat_minor": 2 }