{"id":2652,"date":"2026-10-20T10:56:49","date_gmt":"2026-10-20T10:56:49","guid":{"rendered":"https:\/\/prwatech.in\/blog\/?p=2652"},"modified":"2026-10-21T10:11:28","modified_gmt":"2026-10-21T10:11:28","slug":"file-handling-in-python-tutorial","status":"publish","type":"post","link":"https:\/\/prwatech.in\/blog\/python\/python-file-handling\/file-handling-in-python-tutorial\/","title":{"rendered":"File Handling in Python"},"content":{"rendered":"<h1><strong><b>File Handling in Python Tutorial: Open, Read, Write and Append<\/b><\/strong><\/h1>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Every variable in your program lives in memory, and memory is wiped the moment the program ends. A user fills in a form, a script calculates a result, a game records a high score, and when the window closes, all of it is gone. To keep anything, a program has to write it to a file.<\/p>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">File handling is how Python reads from files and writes to them. It lets you store results, load data, keep logs, and share information between programs. A text file of customer names, a CSV of sales, a log of errors and a saved configuration are all handled the same way. Once you know the basic steps, you can work with any of them.<\/p>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">In this tutorial, we cover the open function and its modes, and then read, readline and readlines, write, append, close and the with statement. We go on to binary files, moving around a file with seek and tell, renaming and deleting files, checking if a file exists, and the errors you will meet. Every example was run on Python 3.13, and the real output is shown. We end with the mistakes beginners make most often and a quick reference.<\/p>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">What is File Handling in Python?<\/h2>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">File handling means creating, opening, reading, writing, changing and closing files from inside a Python program. A file stores data on your disk, so it stays after the program stops, and the next run of the program can read it back.<\/p>\n<h3 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 21px; line-height: 1.35; font-weight: bold; color: #0f2a4a; margin: 28px 0 10px;\">How Python Handles Files<\/h3>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Every file operation follows the same three steps.<\/p>\n<ol style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px; padding-left: 28px;\">\n<li style=\"margin: 0 0 8px;\"><strong>Open<\/strong> the file, which gives you a file object. You say which file, and what you want to do with it.<\/li>\n<li style=\"margin: 0 0 8px;\"><strong>Work<\/strong> on it. Read from it, write to it, or move around inside it.<\/li>\n<li style=\"margin: 0 0 8px;\"><strong>Close<\/strong> it, so the data is saved and the file is released for other programs.<\/li>\n<\/ol>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The file object is the link between your program and the file on disk. All the methods in this tutorial, such as <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">read<\/code> and <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">write<\/code>, belong to it.<\/p>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">Python File Handling Operations<\/h2>\n<h3 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 21px; line-height: 1.35; font-weight: bold; color: #0f2a4a; margin: 28px 0 10px;\">Use of open()<\/h3>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">open<\/code> function opens a file and returns a file object. Its basic form looks like this:<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">file_object = open(file_name, mode, buffering)<\/pre>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The name <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">file_object<\/code> is just a variable, so it is written with an underscore. Only the first argument is required.<\/p>\n<div style=\"border: 1px solid #d9e0ea; border-radius: 8px; overflow-x: auto; margin: 20px 0; -webkit-overflow-scrolling: touch;\">\n<table style=\"width: 100%; min-width: 680px; border-collapse: collapse; font-family: Arial,Helvetica,sans-serif; font-size: 16px; line-height: 1.6; color: #1f2937;\">\n<caption style=\"caption-side: top; text-align: left; padding: 14px 16px; font-weight: bold; font-size: 17px; color: #0f2a4a;\">Arguments of open<\/caption>\n<thead>\n<tr>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38; width: 140px;\" scope=\"col\">Argument<\/th>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38;\" scope=\"col\">What it means<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">file_name<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">The name or path of the file, as text, such as &#8220;test.txt&#8221;<\/td>\n<\/tr>\n<tr style=\"background: #f5f8fc;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">mode<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">A short text that says what you want to do, such as &#8220;r&#8221; to read. The default is &#8220;r&#8221;<\/td>\n<\/tr>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">buffering<\/th>\n<td style=\"padding: 12px 16px;\">Optional. The default is minus 1, which means the system chooses. A value of 0 turns buffering off, and that is only allowed for binary files<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The mode is text, and the default for buffering is minus 1. In text mode, a value of 0 gives this error:<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">try:\r\n    open(\"test.txt\", \"w\", 0)\r\nexcept ValueError as e:\r\n    print(\"ValueError:\", e)<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">ValueError: can't have unbuffered text I\/O<\/pre>\n<\/div>\n<h3 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 21px; line-height: 1.35; font-weight: bold; color: #0f2a4a; margin: 28px 0 10px;\">Modes for Opening a File<\/h3>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The mode decides what you can do with the file, and what happens if it exists or does not. Four letters set the main action, and one more adds detail.<\/p>\n<div style=\"border: 1px solid #d9e0ea; border-radius: 8px; overflow-x: auto; margin: 20px 0; -webkit-overflow-scrolling: touch;\">\n<table style=\"width: 100%; min-width: 760px; border-collapse: collapse; font-family: Arial,Helvetica,sans-serif; font-size: 16px; line-height: 1.6; color: #1f2937;\">\n<caption style=\"caption-side: top; text-align: left; padding: 14px 16px; font-weight: bold; font-size: 17px; color: #0f2a4a;\">File modes<\/caption>\n<thead>\n<tr>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38; width: 90px;\" scope=\"col\">Mode<\/th>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38;\" scope=\"col\">Name<\/th>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38;\" scope=\"col\">What it does<\/th>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38;\" scope=\"col\">If the file is missing<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">&#8220;r&#8221;<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Read<\/td>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Opens for reading. This is the default<\/td>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">FileNotFoundError<\/td>\n<\/tr>\n<tr style=\"background: #f5f8fc;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">&#8220;w&#8221;<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Write<\/td>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Opens for writing and erases the old content<\/td>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Creates the file<\/td>\n<\/tr>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">&#8220;a&#8221;<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Append<\/td>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Opens for writing at the end, and keeps the old content<\/td>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Creates the file<\/td>\n<\/tr>\n<tr style=\"background: #f5f8fc;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">&#8220;x&#8221;<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Create<\/td>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Creates a new file for writing<\/td>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Creates the file. If it already exists, raises FileExistsError<\/td>\n<\/tr>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">&#8220;r+&#8221;<\/th>\n<td style=\"padding: 12px 16px;\">Read and write<\/td>\n<td style=\"padding: 12px 16px;\">Reads and writes, without erasing<\/td>\n<td style=\"padding: 12px 16px;\">FileNotFoundError<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Two more letters can be added to any of these.<\/p>\n<div style=\"border: 1px solid #d9e0ea; border-radius: 8px; overflow-x: auto; margin: 20px 0; -webkit-overflow-scrolling: touch;\">\n<table style=\"width: 100%; min-width: 640px; border-collapse: collapse; font-family: Arial,Helvetica,sans-serif; font-size: 16px; line-height: 1.6; color: #1f2937;\">\n<caption style=\"caption-side: top; text-align: left; padding: 14px 16px; font-weight: bold; font-size: 17px; color: #0f2a4a;\">Text and binary letters<\/caption>\n<thead>\n<tr>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38; width: 90px;\" scope=\"col\">Letter<\/th>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38;\" scope=\"col\">Name<\/th>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38;\" scope=\"col\">What it does<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">t<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Text<\/td>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Works with text. This is the default, so &#8220;r&#8221; and &#8220;rt&#8221; are the same<\/td>\n<\/tr>\n<tr style=\"background: #f5f8fc;\">\n<th style=\"text-align: left; padding: 12px 16px; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">b<\/th>\n<td style=\"padding: 12px 16px;\">Binary<\/td>\n<td style=\"padding: 12px 16px;\">Works with raw bytes, as in images and PDFs. Used as &#8220;rb&#8221;, &#8220;wb&#8221; and &#8220;rb+&#8221;<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Text and binary are not modes that create files. They only change how the file is read or written, and &#8220;rt&#8221; and &#8220;rb&#8221; only read. Pay attention to two details in the table above. Write mode erases the old content, and create mode raises an error if the file already exists. Both are shown next.<\/p>\n<h3 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 21px; line-height: 1.35; font-weight: bold; color: #0f2a4a; margin: 28px 0 10px;\">Write Mode<\/h3>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Write mode creates the file if it is not there. If it is there, it erases everything inside first. This is the most common way to lose data by accident.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">f = open(\"test.txt\", \"w\")\r\nf.write(\"Writing in this file\\n\")\r\nf.write(\"Second line\\n\")\r\nf.write(\"Third line\\n\")\r\nf.close()<\/pre>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">write<\/code> method does not add a new line for you. We put <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">\\n<\/code> at the end of each line, which means a line break. The method gives no output, but the file now holds three lines.<\/p>\n<h3 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 21px; line-height: 1.35; font-weight: bold; color: #0f2a4a; margin: 28px 0 10px;\">Read Mode<\/h3>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Read mode opens an existing file for reading. It is the default, so <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">open(\"test.txt\")<\/code> means the same as <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">open(\"test.txt\", \"r\")<\/code>.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">f = open(\"test.txt\", \"r\")\r\nprint(f.read())\r\nf.close()<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">Writing in this file\r\nSecond line\r\nThird line<\/pre>\n<\/div>\n<h3 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 21px; line-height: 1.35; font-weight: bold; color: #0f2a4a; margin: 28px 0 10px;\">Append Mode<\/h3>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Append mode keeps what is already in the file and adds the new text at the end.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">f = open(\"test.txt\", \"a\")\r\nf.write(\"Adding this line to file\\n\")\r\nf.close()\r\nf = open(\"test.txt\", \"r\")\r\nprint(f.read())\r\nf.close()<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">Writing in this file\r\nSecond line\r\nThird line\r\nAdding this line to file<\/pre>\n<\/div>\n<h3 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 21px; line-height: 1.35; font-weight: bold; color: #0f2a4a; margin: 28px 0 10px;\">Create Mode<\/h3>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Create mode makes a new file, and refuses to touch one that already exists. It is the safe choice when you must not overwrite anything. The second part of the example creates a new file, which we delete later.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">import os\r\n\r\ntry:\r\n    f = open(\"test.txt\", \"x\")\r\nexcept FileExistsError as e:\r\n    print(\"FileExistsError:\", e)\r\nf = open(\"brand_new.txt\", \"x\")\r\nf.close()\r\nprint(os.path.exists(\"brand_new.txt\"))<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">FileExistsError: [Errno 17] File exists: 'test.txt'\r\nTrue<\/pre>\n<\/div>\n<h3 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 21px; line-height: 1.35; font-weight: bold; color: #0f2a4a; margin: 28px 0 10px;\">Read and Write Mode<\/h3>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The mode <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">r+<\/code> lets you read and write in the same file, and it does not erase the content. The writing starts wherever the pointer is. After a full read, the pointer is at the end, so the new text is added there. First we make a small file, which also shows that write mode erases the old content.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">f = open(\"notes.txt\", \"w\")\r\nf.write(\"Fresh start\\n\")\r\nf.close()<\/pre>\n<\/div>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">f = open(\"notes.txt\", \"r+\")\r\nprint(repr(f.read()))\r\nf.write(\"Added after reading\\n\")\r\nf.seek(0)\r\nprint(repr(f.read()))\r\nf.close()<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">'Fresh start\\n'\r\n'Fresh start\\nAdded after reading\\n'<\/pre>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The file held one line, Fresh start. The function <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">repr<\/code> shows the line breaks as <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">\\n<\/code> so you can see them.<\/p>\n<h3 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 21px; line-height: 1.35; font-weight: bold; color: #0f2a4a; margin: 28px 0 10px;\">Text Mode and Binary Mode<\/h3>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Text mode is the default. Python turns the bytes in the file into text for you. Binary mode gives you the raw bytes, and you need it for images, audio, PDFs and any file that is not plain text. Add the letter b to the mode.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">data = bytes([72, 101, 108, 108, 111])\r\nf = open(\"data.bin\", \"wb\")\r\nf.write(data)\r\nf.close()\r\nf = open(\"data.bin\", \"rb\")\r\nprint(f.read())\r\nf.close()\r\nf = open(\"data.bin\", \"rb+\")\r\nprint(f.read(2))\r\nf.close()<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">b'Hello'\r\nb'He'<\/pre>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The mode <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">rb+<\/code> reads and writes bytes. The b before the quotes in the output means the result is bytes and not text.<\/p>\n<h3 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 21px; line-height: 1.35; font-weight: bold; color: #0f2a4a; margin: 28px 0 10px;\">Use of read()<\/h3>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Without a number, <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">read<\/code> returns the whole file as one text. With a number, it returns that many characters. A common mistake is to call it twice on the same open file and expect the second call to give the first four characters. First, we write the three lines again, so the next examples are easy to follow.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">with open(\"test.txt\", \"w\") as f:\r\n    f.write(\"Writing in this file\\nSecond line\\nThird line\\n\")<\/pre>\n<\/div>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">f = open(\"test.txt\", \"r\")\r\nprint(repr(f.read()))\r\nprint(repr(f.read(4)))\r\nf.close()<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">'Writing in this file\\nSecond line\\nThird line\\n'\r\n''<\/pre>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The second call returns an empty text, because the first call already read to the end. A file keeps a position, called the pointer, and every read moves it forward. To get the first four characters, read them on a fresh file object, or move the pointer back to the start with <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">seek<\/code>.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">f = open(\"test.txt\", \"r\")\r\nprint(repr(f.read(4)))\r\nprint(f.tell())\r\nf.seek(0)\r\nprint(repr(f.read(7)))\r\nf.close()<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">'Writ'\r\n4\r\n'Writing'<\/pre>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The method <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">tell<\/code> gives the pointer position, and <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">seek(0)<\/code> moves it back to the start.<\/p>\n<h3 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 21px; line-height: 1.35; font-weight: bold; color: #0f2a4a; margin: 28px 0 10px;\">Use of readline() and readlines()<\/h3>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">These are two different methods, and they are often mixed up.<\/p>\n<div style=\"border: 1px solid #d9e0ea; border-radius: 8px; overflow-x: auto; margin: 20px 0; -webkit-overflow-scrolling: touch;\">\n<table style=\"width: 100%; min-width: 560px; border-collapse: collapse; font-family: Arial,Helvetica,sans-serif; font-size: 16px; line-height: 1.6; color: #1f2937;\">\n<caption style=\"caption-side: top; text-align: left; padding: 14px 16px; font-weight: bold; font-size: 17px; color: #0f2a4a;\">read, readline and readlines<\/caption>\n<thead>\n<tr>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38; width: 150px;\" scope=\"col\">Method<\/th>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38;\" scope=\"col\">What it returns<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">read()<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">The whole file as one text<\/td>\n<\/tr>\n<tr style=\"background: #f5f8fc;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">readline()<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">One line, including its line break. Each call gives the next line<\/td>\n<\/tr>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">readlines()<\/th>\n<td style=\"padding: 12px 16px;\">A list of all the lines<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">f = open(\"test.txt\", \"r\")\r\nprint(repr(f.readline()))\r\nprint(repr(f.readline()))\r\nf.close()\r\n \r\nf = open(\"test.txt\", \"r\")\r\nlines = f.readlines()\r\nprint(lines)\r\nprint(len(lines))\r\nf.close()<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">'Writing in this file\\n'\r\n'Second line\\n'\r\n['Writing in this file\\n', 'Second line\\n', 'Third line\\n']\r\n3<\/pre>\n<\/div>\n<h3 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 21px; line-height: 1.35; font-weight: bold; color: #0f2a4a; margin: 28px 0 10px;\">Loop Over a File Line by Line<\/h3>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">For large files, do not read everything into memory. Loop over the file object, and Python gives you one line at a time.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">f = open(\"test.txt\", \"r\")\r\nfor number, line in enumerate(f, start=1):\r\n    print(number, line.strip())\r\nf.close()<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">1 Writing in this file\r\n2 Second line\r\n3 Third line<\/pre>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">strip<\/code> method removes the line break at the end of each line, so <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">print<\/code> does not add a blank line.<\/p>\n<h3 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 21px; line-height: 1.35; font-weight: bold; color: #0f2a4a; margin: 28px 0 10px;\">Use of close()<\/h3>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">close<\/code> method saves any waiting data and releases the file. If you forget to close a file you have written to, some of your data may never reach the disk. A closed file cannot be read again:<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">f = open(\"test.txt\")\r\nf.close()\r\ntry:\r\n    f.read()\r\nexcept ValueError as e:\r\n    print(\"ValueError:\", e)<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">ValueError: I\/O operation on closed file.<\/pre>\n<\/div>\n<h3 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 21px; line-height: 1.35; font-weight: bold; color: #0f2a4a; margin: 28px 0 10px;\">The with Statement: The Better Way<\/h3>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Writing <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">close<\/code> by hand is easy to forget, and it is skipped when an error happens. The <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">with<\/code> statement fixes this. It closes the file for you when the block ends, even if there is an error. Most Python programmers use this form all the time.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">with open(\"notes.txt\") as f:\r\n    content = f.read()\r\nprint(f.closed)\r\nprint(content.splitlines())<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">True\r\n['Fresh start', 'Added after reading']<\/pre>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The line <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">print(f.closed)<\/code> shows True, so the file was closed automatically after the block.<\/p>\n<h3 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 21px; line-height: 1.35; font-weight: bold; color: #0f2a4a; margin: 28px 0 10px;\">Use of write() and writelines()<\/h3>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">write<\/code> method takes one text. To write several lines at once, use <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">writelines<\/code> with a list. It does not add line breaks either, so put them in the list.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">with open(\"list.txt\", \"w\") as f:\r\n    f.writelines([\"apple\\n\", \"banana\\n\", \"cherry\\n\"])\r\nwith open(\"list.txt\") as f:\r\n    print([line.strip() for line in f])<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">['apple', 'banana', 'cherry']<\/pre>\n<\/div>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">Renaming a File<\/h2>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Renaming uses the <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">os<\/code> module. Here is the correct form, followed by what happens when the file is missing.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">import os\r\n \r\nos.rename(\"test.txt\", \"python_file.txt\")\r\nprint(os.path.exists(\"test.txt\"), os.path.exists(\"python_file.txt\"))\r\ntry:\r\n    os.rename(\"test.txt\", \"other.txt\")\r\nexcept FileNotFoundError as e:\r\n    print(\"FileNotFoundError:\", e)<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">False True\r\nFileNotFoundError: [Errno 2] No such file or directory: 'test.txt' -&gt; 'other.txt'<\/pre>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The first rename works, so test.txt is gone and python_file.txt exists. The second rename fails, because test.txt is no longer there.<\/p>\n<div style=\"position: relative; width: 100%; max-width: 560px; margin: 20px auto; padding-bottom: 56.25%; height: 0; overflow: hidden; border-radius: 8px;\"><iframe style=\"position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0;\" title=\"Python file handling video\" src=\"https:\/\/www.youtube.com\/embed\/IdGoSKoO9Bk\" allowfullscreen=\"allowfullscreen\"><\/iframe><\/div>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">Deleting a File and Checking If It Exists<\/h2>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Use <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">os.remove<\/code> to delete a file, and <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">os.path.exists<\/code> to check first. Deleting is permanent, because the file does not go to the recycle bin.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">import os\r\n \r\nos.remove(\"brand_new.txt\")\r\nprint(sorted(os.listdir(\".\")))\r\nfor name in (\"python_file.txt\", \"missing.txt\"):\r\n    if os.path.exists(name):\r\n        print(name, \"exists, size\", os.path.getsize(name), \"bytes\")\r\n    else:\r\n        print(name, \"does not exist\")<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">['data.bin', 'list.txt', 'notes.txt', 'python_file.txt']\r\npython_file.txt exists, size 44 bytes\r\nmissing.txt does not exist<\/pre>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The listing shows the other files we created earlier in this tutorial.<\/p>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">Handling File Errors<\/h2>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Files go wrong often, since a file can be missing, locked or without permission. Wrap the open call in try and except so the program can respond.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">try:\r\n    open(\"missing.txt\")\r\nexcept FileNotFoundError:\r\n    print(\"File not found\")<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">File not found<\/pre>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Our exception handling tutorial covers try, except, else and finally in full.<\/p>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">Working With Hindi and Other Languages<\/h2>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">If a file holds text that is not plain English, such as Hindi, Bengali or Arabic, give the encoding when you open it. The standard choice is <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">utf-8<\/code>. Without it, the result can depend on your computer, and the text can come out broken on another.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">with open(\"hindi.txt\", \"w\", encoding=\"utf-8\") as f:\r\n    f.write(\"\u0928\u092e\u0938\u094d\u0924\u0947 Python\\n\")\r\nwith open(\"hindi.txt\", encoding=\"utf-8\") as f:\r\n    print(f.read().strip())<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">\u0928\u092e\u0938\u094d\u0924\u0947 Python<\/pre>\n<\/div>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">A Shorter Way With pathlib<\/h2>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">For small text files, the <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">pathlib<\/code> module reads and writes in one line, and handles the open and close for you.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">from pathlib import Path\r\n \r\np = Path(\"note.txt\")\r\np.write_text(\"Short and simple\\n\")\r\nprint(p.read_text().strip())<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">Short and simple<\/pre>\n<\/div>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">Common Mistakes in Python File Handling<\/h2>\n<ul style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px; padding-left: 24px;\">\n<li style=\"margin: 0 0 8px;\"><strong>Using w when you meant a.<\/strong> Write mode erases the file, and the old data is gone. Use <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">a<\/code> to add.<\/li>\n<li style=\"margin: 0 0 8px;\"><strong>Reading twice from the same open file.<\/strong> The second read gives an empty text, because the pointer is at the end. Use <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">seek(0)<\/code> or open the file again.<\/li>\n<li style=\"margin: 0 0 8px;\"><strong>Forgetting to close.<\/strong> Use <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">with open<\/code> so you never need to.<\/li>\n<li style=\"margin: 0 0 8px;\"><strong>Mixing up read, readline and readlines.<\/strong> One gives the whole text, one gives a line, and one gives a list.<\/li>\n<li style=\"margin: 0 0 8px;\"><strong>Forgetting the line break.<\/strong> The <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">write<\/code> method does not add one.<\/li>\n<li style=\"margin: 0 0 8px;\"><strong>Opening a missing file in r mode.<\/strong> It raises <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">FileNotFoundError<\/code>. Check with <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">os.path.exists<\/code>, or catch the error.<\/li>\n<li style=\"margin: 0 0 8px;\"><strong>Forgetting the encoding for non English text.<\/strong> Add <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">encoding=\"utf-8\"<\/code>.<\/li>\n<li style=\"margin: 0 0 8px;\"><strong>Curly quotes and missing spaces in code.<\/strong> Text copied from a web page can turn straight quotes into curly ones, and <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">importos<\/code> is a syntax error.<\/li>\n<\/ul>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">Quick Reference<\/h2>\n<div style=\"border: 1px solid #d9e0ea; border-radius: 8px; overflow-x: auto; margin: 20px 0; -webkit-overflow-scrolling: touch;\">\n<table style=\"width: 100%; min-width: 640px; border-collapse: collapse; font-family: Arial,Helvetica,sans-serif; font-size: 16px; line-height: 1.6; color: #1f2937;\">\n<caption style=\"caption-side: top; text-align: left; padding: 14px 16px; font-weight: bold; font-size: 17px; color: #0f2a4a;\">File handling quick reference<\/caption>\n<thead>\n<tr>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38; width: 240px;\" scope=\"col\">Task<\/th>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38;\" scope=\"col\">Code<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; white-space: nowrap;\" scope=\"row\">Read the whole file<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\">with open(&#8220;a.txt&#8221;) as f: text = f.read()<\/td>\n<\/tr>\n<tr style=\"background: #f5f8fc;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; white-space: nowrap;\" scope=\"row\">Read line by line<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\">for line in f:<\/td>\n<\/tr>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; white-space: nowrap;\" scope=\"row\">Get all lines as a list<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\">f.readlines()<\/td>\n<\/tr>\n<tr style=\"background: #f5f8fc;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; white-space: nowrap;\" scope=\"row\">Write, erasing old content<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\">open(&#8220;a.txt&#8221;, &#8220;w&#8221;)<\/td>\n<\/tr>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; white-space: nowrap;\" scope=\"row\">Add to the end<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\">open(&#8220;a.txt&#8221;, &#8220;a&#8221;)<\/td>\n<\/tr>\n<tr style=\"background: #f5f8fc;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; white-space: nowrap;\" scope=\"row\">Create only if new<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\">open(&#8220;a.txt&#8221;, &#8220;x&#8221;)<\/td>\n<\/tr>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; white-space: nowrap;\" scope=\"row\">Rename<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\">os.rename(&#8220;old&#8221;, &#8220;new&#8221;)<\/td>\n<\/tr>\n<tr style=\"background: #f5f8fc;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; white-space: nowrap;\" scope=\"row\">Delete<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\">os.remove(&#8220;a.txt&#8221;)<\/td>\n<\/tr>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; color: #0f2a4a; white-space: nowrap;\" scope=\"row\">Check if it exists<\/th>\n<td style=\"padding: 12px 16px; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\">os.path.exists(&#8220;a.txt&#8221;)<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">Complete Script to Run Yourself<\/h2>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Here is the full script used to produce every output on this page, in the same order. It works inside a temporary folder, so it will not touch any of your real files. Copy it into a file, run it with Python 3, and compare the results.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">import os\r\nimport tempfile\r\n \r\n# Run everything inside a temporary folder so no real files are touched\r\nworkdir = tempfile.TemporaryDirectory()\r\nos.chdir(workdir.name)\r\n\r\n# 1. buffering 0 in text mode\r\ntry:\r\n    open(\"test.txt\", \"w\", 0)\r\nexcept ValueError as e:\r\n    print(\"ValueError:\", e)\r\n\r\n# 2. Write mode\r\nf = open(\"test.txt\", \"w\")\r\nf.write(\"Writing in this file\\n\")\r\nf.write(\"Second line\\n\")\r\nf.write(\"Third line\\n\")\r\nf.close()\r\n\r\n# 3. Read mode\r\nf = open(\"test.txt\", \"r\")\r\nprint(f.read())\r\nf.close()\r\n\r\n# 4. Append mode\r\nf = open(\"test.txt\", \"a\")\r\nf.write(\"Adding this line to file\\n\")\r\nf.close()\r\nf = open(\"test.txt\", \"r\")\r\nprint(f.read())\r\nf.close()\r\n\r\n# 5. Create mode\r\ntry:\r\n    f = open(\"test.txt\", \"x\")\r\nexcept FileExistsError as e:\r\n    print(\"FileExistsError:\", e)\r\nf = open(\"brand_new.txt\", \"x\")\r\nf.close()\r\nprint(os.path.exists(\"brand_new.txt\"))\r\n\r\n# 6. Fresh file\r\nf = open(\"notes.txt\", \"w\")\r\nf.write(\"Fresh start\\n\")\r\nf.close()\r\n\r\n# 7. r+ mode\r\nf = open(\"notes.txt\", \"r+\")\r\nprint(repr(f.read()))\r\nf.write(\"Added after reading\\n\")\r\nf.seek(0)\r\nprint(repr(f.read()))\r\nf.close()\r\n\r\n# 8. Binary mode\r\ndata = bytes([72, 101, 108, 108, 111])\r\nf = open(\"data.bin\", \"wb\")\r\nf.write(data)\r\nf.close()\r\nf = open(\"data.bin\", \"rb\")\r\nprint(f.read())\r\nf.close()\r\nf = open(\"data.bin\", \"rb+\")\r\nprint(f.read(2))\r\nf.close()\r\n\r\n# 9. Reset file\r\nwith open(\"test.txt\", \"w\") as f:\r\n    f.write(\"Writing in this file\\nSecond line\\nThird line\\n\")\r\n\r\n# 10. read twice\r\nf = open(\"test.txt\", \"r\")\r\nprint(repr(f.read()))\r\nprint(repr(f.read(4)))\r\nf.close()\r\n\r\n# 11. tell and seek\r\nf = open(\"test.txt\", \"r\")\r\nprint(repr(f.read(4)))\r\nprint(f.tell())\r\nf.seek(0)\r\nprint(repr(f.read(7)))\r\nf.close()\r\n\r\n# 12. readline and readlines\r\nf = open(\"test.txt\", \"r\")\r\nprint(repr(f.readline()))\r\nprint(repr(f.readline()))\r\nf.close()\r\n \r\nf = open(\"test.txt\", \"r\")\r\nlines = f.readlines()\r\nprint(lines)\r\nprint(len(lines))\r\nf.close()\r\n\r\n# 13. loop\r\nf = open(\"test.txt\", \"r\")\r\nfor number, line in enumerate(f, start=1):\r\n    print(number, line.strip())\r\nf.close()\r\n\r\n# 14. closed file\r\nf = open(\"test.txt\")\r\nf.close()\r\ntry:\r\n    f.read()\r\nexcept ValueError as e:\r\n    print(\"ValueError:\", e)\r\n\r\n# 15. with\r\nwith open(\"notes.txt\") as f:\r\n    content = f.read()\r\nprint(f.closed)\r\nprint(content.splitlines())\r\n\r\n# 16. writelines\r\nwith open(\"list.txt\", \"w\") as f:\r\n    f.writelines([\"apple\\n\", \"banana\\n\", \"cherry\\n\"])\r\nwith open(\"list.txt\") as f:\r\n    print([line.strip() for line in f])\r\n\r\n# 17. rename\r\nos.rename(\"test.txt\", \"python_file.txt\")\r\nprint(os.path.exists(\"test.txt\"), os.path.exists(\"python_file.txt\"))\r\ntry:\r\n    os.rename(\"test.txt\", \"other.txt\")\r\nexcept FileNotFoundError as e:\r\n    print(\"FileNotFoundError:\", e)\r\n\r\n# 18. remove and exists\r\nos.remove(\"brand_new.txt\")\r\nprint(sorted(os.listdir(\".\")))\r\nfor name in (\"python_file.txt\", \"missing.txt\"):\r\n    if os.path.exists(name):\r\n        print(name, \"exists, size\", os.path.getsize(name), \"bytes\")\r\n    else:\r\n        print(name, \"does not exist\")\r\n\r\n# 19. file error\r\ntry:\r\n    open(\"missing.txt\")\r\nexcept FileNotFoundError:\r\n    print(\"File not found\")\r\n\r\n# 20. hindi\r\nwith open(\"hindi.txt\", \"w\", encoding=\"utf-8\") as f:\r\n    f.write(\"\u0928\u092e\u0938\u094d\u0924\u0947 Python\\n\")\r\nwith open(\"hindi.txt\", encoding=\"utf-8\") as f:\r\n    print(f.read().strip())\r\n\r\n# 21. pathlib\r\nfrom pathlib import Path\r\n \r\np = Path(\"note.txt\")\r\np.write_text(\"Short and simple\\n\")\r\nprint(p.read_text().strip())<\/pre>\n<\/div>\n<p>File handling comes down to a short habit: open the file with the right mode, do your work, and let the with statement close it. Choose w, a and x with care, remember that the pointer moves as you read, and always handle the case where the file is missing. Run the script above, change the modes, and watch what the files do. Then try reading a real CSV file, and look at the csv and json modules for structured data.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>File Handling in Python Tutorial: Open, Read, Write and Append Every variable in your program lives in memory, and memory is wiped the moment the program ends. A user fills in a form, a script calculates a result, a game records a high score, and when the window closes, all of it is gone. To [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":3427,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[28,1672],"tags":[400,77,540,537,401,545,547],"class_list":["post-2652","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","category-python-file-handling","tag-file-handling-in-python-tutorial","tag-file-handling-in-python-tutorial-with-example","tag-online-course-to-learn-python","tag-online-training-on-python","tag-python-file-handling-operations","tag-python-training-course-online","tag-python-training-online"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v25.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>File Handling in Python: Open, Read, Write and Append | PrwaTech<\/title>\n<meta name=\"description\" content=\"Learn Python file handling with tested examples: open modes, read, readline, write, append, with statement, rename, delete and file errors.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/prwatech.in\/blog\/python\/python-file-handling\/file-handling-in-python-tutorial\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"File Handling in Python: Open, Read, Write and Append | PrwaTech\" \/>\n<meta property=\"og:description\" content=\"Learn Python file handling with tested examples: open modes, read, readline, write, append, with statement, rename, delete and file errors.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/prwatech.in\/blog\/python\/python-file-handling\/file-handling-in-python-tutorial\/\" \/>\n<meta property=\"og:site_name\" content=\"Prwatech\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/prwatech.in\/\" \/>\n<meta property=\"article:published_time\" content=\"2026-10-20T10:56:49+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-10-21T10:11:28+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2019\/07\/File-Handling-in-Python.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"960\" \/>\n\t<meta property=\"og:image:height\" content=\"550\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Prwatech\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@Eduprwatech\" \/>\n<meta name=\"twitter:site\" content=\"@Eduprwatech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Prwatech\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"9 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/prwatech.in\/blog\/python\/python-file-handling\/file-handling-in-python-tutorial\/\",\"url\":\"https:\/\/prwatech.in\/blog\/python\/python-file-handling\/file-handling-in-python-tutorial\/\",\"name\":\"File Handling in Python: Open, Read, Write and Append | PrwaTech\",\"isPartOf\":{\"@id\":\"https:\/\/prwatech.in\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/prwatech.in\/blog\/python\/python-file-handling\/file-handling-in-python-tutorial\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/prwatech.in\/blog\/python\/python-file-handling\/file-handling-in-python-tutorial\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2019\/07\/File-Handling-in-Python.jpg\",\"datePublished\":\"2026-10-20T10:56:49+00:00\",\"dateModified\":\"2026-10-21T10:11:28+00:00\",\"author\":{\"@id\":\"https:\/\/prwatech.in\/blog\/#\/schema\/person\/db90baff7744090b2288bbc98fea87f3\"},\"description\":\"Learn Python file handling with tested examples: open modes, read, readline, write, append, with statement, rename, delete and file errors.\",\"breadcrumb\":{\"@id\":\"https:\/\/prwatech.in\/blog\/python\/python-file-handling\/file-handling-in-python-tutorial\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/prwatech.in\/blog\/python\/python-file-handling\/file-handling-in-python-tutorial\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/prwatech.in\/blog\/python\/python-file-handling\/file-handling-in-python-tutorial\/#primaryimage\",\"url\":\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2019\/07\/File-Handling-in-Python.jpg\",\"contentUrl\":\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2019\/07\/File-Handling-in-Python.jpg\",\"width\":960,\"height\":550,\"caption\":\"File Handling in Python\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/prwatech.in\/blog\/python\/python-file-handling\/file-handling-in-python-tutorial\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/prwatech.in\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"File Handling in Python\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/prwatech.in\/blog\/#website\",\"url\":\"https:\/\/prwatech.in\/blog\/\",\"name\":\"Prwatech\",\"description\":\"Share Ideas, Start Something Good.\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/prwatech.in\/blog\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/prwatech.in\/blog\/#\/schema\/person\/db90baff7744090b2288bbc98fea87f3\",\"name\":\"Prwatech\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/prwatech.in\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/c00bafc1b04045f31eda917de39891456c44fa47c092b9bb6be0f860a3a30a2f?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/c00bafc1b04045f31eda917de39891456c44fa47c092b9bb6be0f860a3a30a2f?s=96&d=mm&r=g\",\"caption\":\"Prwatech\"},\"url\":\"https:\/\/prwatech.in\/blog\/author\/prwatech123\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"File Handling in Python: Open, Read, Write and Append | PrwaTech","description":"Learn Python file handling with tested examples: open modes, read, readline, write, append, with statement, rename, delete and file errors.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/prwatech.in\/blog\/python\/python-file-handling\/file-handling-in-python-tutorial\/","og_locale":"en_US","og_type":"article","og_title":"File Handling in Python: Open, Read, Write and Append | PrwaTech","og_description":"Learn Python file handling with tested examples: open modes, read, readline, write, append, with statement, rename, delete and file errors.","og_url":"https:\/\/prwatech.in\/blog\/python\/python-file-handling\/file-handling-in-python-tutorial\/","og_site_name":"Prwatech","article_publisher":"https:\/\/www.facebook.com\/prwatech.in\/","article_published_time":"2026-10-20T10:56:49+00:00","article_modified_time":"2026-10-21T10:11:28+00:00","og_image":[{"width":960,"height":550,"url":"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2019\/07\/File-Handling-in-Python.jpg","type":"image\/jpeg"}],"author":"Prwatech","twitter_card":"summary_large_image","twitter_creator":"@Eduprwatech","twitter_site":"@Eduprwatech","twitter_misc":{"Written by":"Prwatech","Est. reading time":"9 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/prwatech.in\/blog\/python\/python-file-handling\/file-handling-in-python-tutorial\/","url":"https:\/\/prwatech.in\/blog\/python\/python-file-handling\/file-handling-in-python-tutorial\/","name":"File Handling in Python: Open, Read, Write and Append | PrwaTech","isPartOf":{"@id":"https:\/\/prwatech.in\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/prwatech.in\/blog\/python\/python-file-handling\/file-handling-in-python-tutorial\/#primaryimage"},"image":{"@id":"https:\/\/prwatech.in\/blog\/python\/python-file-handling\/file-handling-in-python-tutorial\/#primaryimage"},"thumbnailUrl":"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2019\/07\/File-Handling-in-Python.jpg","datePublished":"2026-10-20T10:56:49+00:00","dateModified":"2026-10-21T10:11:28+00:00","author":{"@id":"https:\/\/prwatech.in\/blog\/#\/schema\/person\/db90baff7744090b2288bbc98fea87f3"},"description":"Learn Python file handling with tested examples: open modes, read, readline, write, append, with statement, rename, delete and file errors.","breadcrumb":{"@id":"https:\/\/prwatech.in\/blog\/python\/python-file-handling\/file-handling-in-python-tutorial\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/prwatech.in\/blog\/python\/python-file-handling\/file-handling-in-python-tutorial\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/prwatech.in\/blog\/python\/python-file-handling\/file-handling-in-python-tutorial\/#primaryimage","url":"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2019\/07\/File-Handling-in-Python.jpg","contentUrl":"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2019\/07\/File-Handling-in-Python.jpg","width":960,"height":550,"caption":"File Handling in Python"},{"@type":"BreadcrumbList","@id":"https:\/\/prwatech.in\/blog\/python\/python-file-handling\/file-handling-in-python-tutorial\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/prwatech.in\/blog\/"},{"@type":"ListItem","position":2,"name":"File Handling in Python"}]},{"@type":"WebSite","@id":"https:\/\/prwatech.in\/blog\/#website","url":"https:\/\/prwatech.in\/blog\/","name":"Prwatech","description":"Share Ideas, Start Something Good.","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/prwatech.in\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/prwatech.in\/blog\/#\/schema\/person\/db90baff7744090b2288bbc98fea87f3","name":"Prwatech","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/prwatech.in\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/c00bafc1b04045f31eda917de39891456c44fa47c092b9bb6be0f860a3a30a2f?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/c00bafc1b04045f31eda917de39891456c44fa47c092b9bb6be0f860a3a30a2f?s=96&d=mm&r=g","caption":"Prwatech"},"url":"https:\/\/prwatech.in\/blog\/author\/prwatech123\/"}]}},"_links":{"self":[{"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/posts\/2652","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/comments?post=2652"}],"version-history":[{"count":19,"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/posts\/2652\/revisions"}],"predecessor-version":[{"id":12054,"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/posts\/2652\/revisions\/12054"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/media\/3427"}],"wp:attachment":[{"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/media?parent=2652"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/categories?post=2652"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/tags?post=2652"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}