codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🐍

Python Programming

45 / 68 topics
45Python File Handling (Read/Write/Delete)46Reading & Writing CSV Files47Python Exception Handling48Python Custom Exceptions
Tutorials/Python Programming/Python File Handling (Read/Write/Delete)
🐍Python Programming

Python File Handling (Read/Write/Delete)

Updated 2026-05-15
30 min read

Python File Handling (Read/Write/Delete)

File handling is a crucial aspect of any programming language, allowing you to interact with the file system. In Python, you can perform various operations such as reading from and writing to files, appending data, creating new files, and deleting existing ones. This tutorial will guide you through these operations using Python's built-in open() function, different file modes, and the with statement for efficient file handling.

Introduction

Understanding how to handle files is essential for any developer as it enables you to work with data stored in external files. Whether you're reading configuration settings, processing large datasets, or saving user-generated content, file handling is a fundamental skill. In this tutorial, we'll explore the basics of opening files, different modes for reading and writing, and how to handle exceptions that may arise during these operations.

Opening Files with open()

The open() function in Python is used to open a file and return a corresponding file object. This file object can then be used to read from or write to the file. The basic syntax of the open() function is:

Python
1file_object = open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
  • file: The path to the file you want to open.
  • mode: The mode in which the file is opened. Common modes include:
    • 'r': Read (default). Opens a file for reading only.
    • 'w': Write. Opens a file for writing only, truncating the file first.
    • 'a': Append. Opens a file for appending at the end of the file without truncating it.
    • 'x': Create. Creates a new file and opens it for writing. Raises an error if the file already exists.
    • 'b': Binary mode. Appends to the mode, e.g., 'rb' or 'wb'.

Reading Files

Once you have opened a file in read mode ('r'), you can use various methods to read its contents.

Using read()

The read() method reads the entire content of the file and returns it as a string.

read_example.py
1with open('example.txt', 'r') as file:
2 content = file.read()
3 print(content)
Output
Hello, world!
This is a sample text file.

Using readline()

The readline() method reads a single line from the file and returns it.

readline_example.py
1with open('example.txt', 'r') as file:
2 first_line = file.readline()
3 print(first_line)
Output
Hello, world!

Using readlines()

The readlines() method reads all lines from the file and returns them as a list of strings.

readlines_example.py
1with open('example.txt', 'r') as file:
2 lines = file.readlines()
3 print(lines)
Output
['Hello, world!
', 'This is a sample text file.
']

Writing Files

To write to a file in Python, you need to open it in write mode ('w'), append mode ('a'), or create mode ('x'). If the file does not exist, opening it in any of these modes will create it.

Using write()

The write() method writes a string to the file.

write_example.py
1with open('output.txt', 'w') as file:
2 file.write("Hello, world!")

After running this code, you will find an output.txt file containing:

Hello, world!

Using writelines()

The writelines() method writes a list of strings to the file.

writelines_example.py
1lines = ["Line 1
2", "Line 2
3", "Line 3
4"]
5with open('output.txt', 'w') as file:
6 file.writelines(lines)

After running this code, you will find an output.txt file containing:

Line 1 Line 2 Line 3

The with Statement

The with statement is highly recommended when dealing with file operations as it ensures that the file is properly closed after its suite finishes, even if an exception is raised. This is crucial for preventing data corruption and resource leaks.

with_example.py
1with open('example.txt', 'r') as file:
2 content = file.read()
3 print(content)
4# File is automatically closed here

Deleting Files

To delete a file in Python, you can use the os.remove() function from the os module.

delete_example.py
1import os
2
3if os.path.exists("output.txt"):
4 os.remove("output.txt")
5 print("File deleted successfully.")
6else:
7 print("The file does not exist.")

Exception Handling

When working with files, it's important to handle exceptions that may occur, such as FileNotFoundError or IOError. Using a try-except block can help manage these errors gracefully.

exception_example.py
1try:
2 with open('nonexistent.txt', 'r') as file:
3 content = file.read()
4except FileNotFoundError:
5 print("The file was not found.")
6except IOError:
7 print("An error occurred while reading the file.")

Practical Example

Let's create a practical example that combines reading from one file, processing its contents, and writing the results to another file.

practical_example.py
1# Read from input.txt
2with open('input.txt', 'r') as infile:
3 lines = infile.readlines()
4
5# Process the lines (e.g., convert to uppercase)
6processed_lines = [line.upper() for line in lines]
7
8# Write to output.txt
9with open('output.txt', 'w') as outfile:
10 outfile.writelines(processed_lines)
11
12print("Processing complete. Check output.txt for results.")

Summary

ConceptDescription
open()Function used to open files with different modes (r, w, a, x, b).
Reading Methodsread(), readline(), readlines() for reading file contents.
Writing Methodswrite(), writelines() for writing data to a file.
with StatementEnsures files are properly closed after their suite finishes.
Deleting FilesUse os.remove() to delete a file if it exists.
Exception HandlingHandle errors like FileNotFoundError and IOError using try-except blocks.

What's Next?

In the next tutorial, we'll explore how to read from and write to CSV files using Python's built-in csv module. This will be particularly useful for handling tabular data in a structured format. Stay tuned!


PreviousPython JSONNext Reading & Writing CSV Files

Recommended Gear

Python JSONReading & Writing CSV Files