🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to Python Notes
Topic #112

Python File Handling


File handling is an important part of any web application.

Python has several functions for creating, reading, updating, and deleting files.


File Handling

The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

<p><code class="w3-codespan">"r"</code> - Read - Default value. Opens a
file for reading, error if the file does not exist</p>
<p><code class="w3-codespan">"a"</code> - Append - Opens a file for
appending, creates the file if it does not exist</p>
<p><code class="w3-codespan">"w"</code> - Write - Opens a file for writing,
creates the file if it does not exist</p>
<p><code class="w3-codespan">"x"</code> - Create - Creates the specified file, returns
an error if the file exists</p>

In addition you can specify if the file should be handled as binary or text mode

<p><code class="w3-codespan">"t"</code> - Text - Default value. Text mode</p>
<p><code class="w3-codespan">"b"</code> - Binary - Binary mode (e.g.
  images)</p>

Syntax

To open a file for reading it is enough to specify the name of the file:

f = open("demofile.txt")

The code above is the same as:

f = open("demofile.txt", "rt")

Because "r" for read, and "t" for text are the default values, you do not need to specify them.

Note: Make sure the file exists, or else you will get an error.

Want to go beyond the notes?

Join CodingNow 2.0's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Python File Handling – FAQs

Quick answers about learning Python File Handling in Python.

This free note from CodingNow 2.0 explains Python File Handling in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on CodingNow 2.0, including Python File Handling, is 100% free with no signup required.
With focused practice, most students grasp Python File Handling in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now