HappiomHappiom
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
Expand All Collapse All
  • Python Examples
    • Basic Syntax
      • Python Example Code to Concat 2 Numbers
      • Python Example Code to Concat N Strings
      • Python Code to Find Perimeter of a Circle
      • Python Code to Convert CSV file to Parquet format
      • Python Code to Get Current Day of Week
      • Python Code to Convert Binary String to Decimal Number Vice versa
      • Python Code to Find Difference Between 2 Strings
      • Python Example Code to Remove Duplicates from a List
      • Python Example Code to Calculate Height of Triangle
      • Python Code to Generate Complex Random Password
    • File Handling
      • Python Code to Write & Read Key Value Pair in File
      • In Python File is Not Opening (How to Fix)
      • Python Code to Read Specific Line from a File
      • Python Code to Clear Contents of a File
      • Python Code to Count and List Files in a Directory
    • Modules and Libraries
      • Python Code for Automation using BDD
      • Python Code to Load .SO File (and Invoke a Function)
    • Object-Oriented Programming
      • Python Code to Create a Class with Attributes
      • Python Code to Define Methods in a Class
    • Python Example Code to Check Internet Connection
    • Example Python Code to Send an Email
    • Python Code to Fetch Data from an API (e.g., OpenWeatherMap)
    • Example Python Code to Extract Text from PDF
    • Python Code to Perform Web Scraping (e.g., Scraping Wikipedia)
    • Example Python Code to Plot Data Using Matplotlib
    • Python Code to Perform Data Analysis with Pandas
    • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
    • Python Code to Handle User Authentication in Flask
    • Example Python Code to interact with databases using libraries like SQLAlchemy

File Handling

File handling is a key part of programming that lets applications work with data on disk. In Python, file handling is done using built-in functions and methods. This allows for reading, writing, and manipulating files. Proper file handling is essential for many tasks, like saving data or managing file contents.

Python uses the `open()` function to handle files. This function provides a file object with various operations. Files can be opened in different modes: read (‘r’), write (‘w’), append (‘a’), and binary (‘b’).

Each mode determines how the file is accessed. For example, ‘r’ is for reading from a file, and ‘w’ is for creating or overwriting a file.

Python also uses context managers with the `with` statement for better resource management. This ensures files are closed properly after use, even if errors occur. Error handling is also important, especially for issues like missing files or permission problems.

You can master these file handling techniques, developers can build reliable applications that manage data effectively.

1. Introduction

File handling in Python involves reading from and writing to files. Python provides built-in functions and methods to handle files in different modes, such as text and binary modes. This capability is essential for many applications, including data processing and configuration management.

2. Opening a File

To work with a file, you first need to open it using the built-in open() function. This function returns a file object, which provides methods and attributes to interact with the file.

  • open(filename, mode): Opens a file where filename is the name of the file and mode specifies the mode in which the file is opened.

3. File Modes

File modes determine the actions you can perform on a file. Common modes include:

  • 'r': Read-only mode. Default mode. The file must exist.
  • 'w': Write-only mode. Creates a new file or truncates an existing file.
  • 'a': Append mode. Adds to the end of the file if it exists; otherwise, creates a new file.
  • 'b': Binary mode. Reads or writes the file in binary format.

4. Reading from a File

Once a file is opened, you can read its contents using methods such as read(), readline(), or readlines().

# Example of reading a file
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)
    # Output will be the content of 'example.txt'

5. Writing to a File

To write data to a file, you use methods like write() or writelines(). Note that writing in ‘w’ mode will overwrite the existing file.

# Example of writing to a file
with open('example.txt', 'w') as file:
    file.write("Hello, World!\n")
    file.write("This is a new line.")

6. Appending to a File

To add data to the end of a file without deleting its current contents, use ‘a’ mode:

# Example of appending to a file
with open('example.txt', 'a') as file:
    file.write("\nThis line is appended.")

7. Working with Binary Files

Binary files are handled similarly to text files but with the binary mode ‘b’. This is useful for files that are not encoded in text (e.g., images, executables).

# Example of reading a binary file
with open('example.jpg', 'rb') as file:
    content = file.read()
    # Process binary content

8. Closing a File

It is good practice to close a file after you are done with it to free up system resources. This is done using the close() method. Using a context manager (the with statement) automatically handles closing the file for you.

# Example of closing a file manually
file = open('example.txt', 'r')
content = file.read()
file.close()

9. Error Handling

When handling files, you should consider handling possible errors such as file not found or permission issues. This can be managed using try-except blocks.

# Example of error handling
try:
    with open('example.txt', 'r') as file:
        content = file.read()
except FileNotFoundError:
    print("The file does not exist.")
except IOError:
    print("Error occurred while handling the file.")

To conclude, file handling is a fundamental aspect of programming in Python. By understanding how to open, read, write, and close files, you can effectively manage data in your applications.

Always handle files with care and ensure proper error handling to make your code robust.

Related Articles
  • Python Example Code to Calculate Height of Triangle
  • Python Example Code to Remove Duplicates from a List
  • Example Python Code to interact with databases using libraries like SQLAlchemy
  • Python Code to Handle User Authentication in Flask
  • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
  • Python Code to Perform Data Analysis with Pandas

No luck finding what you need? Contact Us

Previously
Python Code to Generate Complex Random Password
Up Next
Python Code to Write & Read Key Value Pair in File
  • About Us
  • Contact Us
  • Archive
  • Hindi
  • Tamil
  • Telugu
  • Marathi
  • Gujarati
  • Malayalam
  • Kannada
  • Privacy Policy
  • Copyright 2026 Happiom. All Rights Reserved.