Python File Handling
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Python File Handling

Kishore V


Python File Handling

File handling plays a crucial role in many applications, especially when working with data storage, logs, uploads, or configuration files.

Python provides built-in functions that allow you to create, read, modify, and remove files easily, without needing extra libraries.

Working with Files in Python

The primary function used for file operations in Python is open().

This function connects your program to a file and returns a file object that you can work with.

Basic Syntax

# Syntax guide - requires valid file to execute
  • filename → Name (or path) of the file
  • mode → Specifies how the file should be opened

File Open Modes

Python provides several modes for opening a file:

Mode Description
"r" Read - Default value. Opens a file for reading, error if the file does not exist
"a" Append - Opens a file for appending, creates the file if it does not exist
"w" Write - Opens a file for writing, creates the file if it does not exist
"x" Create - Creates the specified file, returns an error if the file exists
"t" Text - Default value. Text mode
"b" Binary - Binary mode (e.g. images)

Example: Binary Modes

Error: image.jpg not found. Opened output.jpg for writing in binary.

Opening a File for Reading

Example: Default Read Mode

File not found.

This works because the default mode is "rt" (Read Text).

Equivalent Code

File not found.

Example: Reading File Content

Hello! Welcome to Python file handling.

Note: Always remember to close the file after finishing operations.

Example: Using with Statement

This file will close automatically!

Note: This approach is cleaner and safer, as it automatically closes the file even if an error occurs.


Our website uses cookies to enhance your experience. Learn More
Accept !