Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Types of Exception
    • Exception Handling
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python: Introduction to File Handling

Python File Handling Introduction - Complete Guide

Learn how to work with files in Python — read, write, and manage data efficiently.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • What is File Handling?
  • Why is File Handling Important?
  • File Modes in Python
  • The File Object
  • Reading from Files
  • Writing to Files
  • The with Statement
  • Error Handling with Files
  • Try It Yourself
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • What is file handling — working with files in Python
  • Why it's important — storing and retrieving data
  • File modes — reading, writing, appending
  • The file object — how Python represents files
  • Reading files — different ways to read
  • Writing files — creating and writing data
  • The with statement — safe file handling

What is File Handling?

File handling is the process of working with files in a computer program. It involves creating, opening, reading, writing, and closing files to store and retrieve data permanently.

Think of a file like a notebook. When you write in a notebook, you're storing information. When you read it later, you're retrieving that information. Similarly, file handling allows your Python programs to store data permanently and retrieve it whenever needed.

💡 Key concept: File handling is essential because it allows programs to store data permanently. Without it, all data would be lost when the program ends. Files enable us to save, share, and process data over time.

Why is File Handling Important?

1

Why We Need File Handling

# Without file handling, all data is temporary

# Variables store data only while the program runs
name = "Alice"
age = 25
# When the program ends, this data is lost forever!

# With file handling, data is permanent

# Save data to a file
with open("user_data.txt", "w") as file:
    file.write("Alice,25")

# Later, you can read it back
with open("user_data.txt", "r") as file:
    data = file.read()
    print(data)  # Alice,25

# Real-world applications of file handling:

# 1. Data Storage and Retrieval
# - User profiles
# - Application settings
# - Game progress

# 2. Data Processing
# - Reading CSV files for analysis
# - Processing log files
# - Handling configuration files

# 3. Data Exchange
# - Reading JSON files from APIs
# - Writing reports
# - Exporting data

# 4. Web Development
# - Serving static files
# - Handling file uploads
# - Generating files for download

# 5. Scientific Computing
# - Reading datasets
# - Saving results
# - Processing large files

Why file handling matters:

  • Permanent storage — data survives after program ends
  • Data exchange — share data between programs
  • Configuration — store settings and preferences
  • Logging — keep records of program activity
  • Data analysis — process large datasets

Quick Check: Why is file handling important? (Answer: It allows permanent storage of data)

File Modes in Python

2

Understanding File Access Modes

# File modes specify how a file is opened

# 1. 'r' - Read mode (default)
# Opens a file for reading
file = open("myfile.txt", 'r')
# You can only read, cannot write
# File must exist, or it raises an error

# 2. 'w' - Write mode
# Opens a file for writing
file = open("myfile.txt", 'w')
# Creates a new file or overwrites existing one
# You can write, cannot read

# 3. 'a' - Append mode
# Opens a file for appending
file = open("myfile.txt", 'a')
# Adds new content at the end of the file
# File is created if it doesn't exist

# 4. 'x' - Exclusive creation
# Creates a new file, fails if it exists
file = open("newfile.txt", 'x')
# Useful for preventing accidental overwrites

# 5. 'r+' - Read and write mode
# Opens a file for both reading and writing
file = open("myfile.txt", 'r+')
# Can read and write, file must exist

# 6. 'w+' - Write and read mode
# Opens a file for writing and reading
file = open("myfile.txt", 'w+')
# Creates new file or overwrites existing

# 7. 'a+' - Append and read mode
# Opens a file for appending and reading
file = open("myfile.txt", 'a+')
# Can append and read, creates if not exists

# Additional 'b' for binary mode
# 'rb' - Read binary
# 'wb' - Write binary
# 'ab' - Append binary

# Mode summary table:
# Mode | Read | Write | Create | Overwrite | Position
# r    | Yes  | No    | No     | No        | Beginning
# w    | No   | Yes   | Yes    | Yes       | Beginning
# a    | No   | Yes   | Yes    | No        | End
# x    | No   | Yes   | Yes    | No        | Beginning
# r+   | Yes  | Yes   | No     | No        | Beginning
# w+   | Yes  | Yes   | Yes    | Yes       | Beginning
# a+   | Yes  | Yes   | Yes    | No        | End

File mode summary:

  • r — Read only (default)
  • w — Write (overwrites)
  • a — Append (adds to end)
  • x — Exclusive creation
  • r+ — Read and write
  • w+ — Write and read
  • a+ — Append and read
  • b — Binary mode (combine with above)

Quick Check: What mode should you use to add content to the end of a file? (Answer: 'a' or append mode)

The File Object

3

Understanding Python's File Object

# When you open a file, Python returns a file object
# This object has methods for reading, writing, and managing files

# Opening a file creates a file object
file = open("example.txt", "r")
print(type(file))  # 

# File object properties
print(f"File name: {file.name}")         # example.txt
print(f"File mode: {file.mode}")         # r
print(f"File closed: {file.closed}")     # False
print(f"File encoding: {file.encoding}") # utf-8

# Common file object methods:
# read()      — Read the entire file
# readline()  — Read one line
# readlines() — Read all lines into a list
# write()     — Write a string to the file
# writelines() — Write a list of strings
# close()     — Close the file
# tell()      — Get current file position
# seek()      — Move to a position in the file
# flush()     — Flush the buffer

# Checking if a file object is readable/writable
if file.readable():
    print("File is readable")
if file.writable():
    print("File is writable")

# Don't forget to close files!
file.close()
print(f"File closed: {file.closed}")  # True

# Trying to operate on a closed file raises an error
# file.read()  # ValueError: I/O operation on closed file

File object key points:

  • File object — returned by open() function
  • Methods — read, write, close, seek, tell
  • Properties — name, mode, closed, encoding
  • Always close — to free system resources

Quick Check: Why should you close files? (Answer: To free system resources and ensure data is saved)

Reading from Files

4

Different Ways to Read Files

# Reading files in Python

# Create a sample file first
with open("sample.txt", "w") as f:
    f.write("Line 1\n")
    f.write("Line 2\n")
    f.write("Line 3\n")

# 1. read() - Read the entire file
with open("sample.txt", "r") as file:
    content = file.read()
    print("Entire file:")
    print(content)

# 2. readline() - Read one line at a time
with open("sample.txt", "r") as file:
    print("\nReading line by line:")
    line1 = file.readline()  # "Line 1\n"
    line2 = file.readline()  # "Line 2\n"
    print(f"Line 1: {line1.strip()}")
    print(f"Line 2: {line2.strip()}")

# 3. readlines() - Read all lines into a list
with open("sample.txt", "r") as file:
    lines = file.readlines()
    print("\nAll lines as list:")
    print(lines)

# 4. Iterating over a file (most efficient)
print("\nIterating over file:")
with open("sample.txt", "r") as file:
    for line in file:
        print(f"Line: {line.strip()}")

# 5. Reading a specific number of characters
with open("sample.txt", "r") as file:
    first_5_chars = file.read(5)
    print(f"First 5 characters: '{first_5_chars}'")

# 6. Reading from a specific position (seek)
with open("sample.txt", "r") as file:
    file.seek(5)  # Move to position 5
    print(f"From position 5: {file.read()}")

# 7. Checking current position (tell)
with open("sample.txt", "r") as file:
    print(f"Position: {file.tell()}")  # 0
    file.read(3)
    print(f"Position: {file.tell()}")  # 3

# Reading non-existent file (error handling)
try:
    with open("nonexistent.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("File not found!")

Reading methods:

  • read() — whole file as a string
  • readline() — one line at a time
  • readlines() — all lines as a list
  • Iteration — most memory-efficient
  • seek()/tell() — move around the file

Quick Check: Which method reads the entire file as a string? (Answer: read())

Writing to Files

5

Creating and Writing Files

# Writing to files in Python

# 1. write() - Write a string
with open("write_example.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("This is a second line.\n")
    file.write("And a third line.\n")

# 2. writelines() - Write a list of strings
with open("writelines_example.txt", "w") as file:
    lines = ["First line\n", "Second line\n", "Third line\n"]
    file.writelines(lines)

# 3. Appending to a file
with open("append_example.txt", "a") as file:
    file.write("This line is appended.\n")
    file.write("So is this one.\n")

# 4. Creating a file with 'x' mode
try:
    with open("new_file.txt", "x") as file:
        file.write("This file is newly created!\n")
except FileExistsError:
    print("File already exists!")

# 5. Writing different data types
with open("data.txt", "w") as file:
    # Convert to string before writing
    number = 42
    name = "Alice"
    file.write(f"Number: {number}\n")
    file.write(f"Name: {name}\n")

# 6. Writing multiple lines with join
data = ["Apple", "Banana", "Cherry"]
with open("fruits.txt", "w") as file:
    file.write("\n".join(data))

# 7. Writing large files efficiently
def write_large_file(filename, num_lines):
    with open(filename, "w") as file:
        for i in range(num_lines):
            file.write(f"Line number: {i}\n")

# write_large_file("large.txt", 10000)

# 8. Checking if writing was successful
with open("test_write.txt", "w") as file:
    written = file.write("Hello, Python!")
    print(f"Characters written: {written}")  # 14

Writing methods:

  • write() — write a single string
  • writelines() — write a list of strings
  • 'w' mode — overwrite existing content
  • 'a' mode — append to the end
  • 'x' mode — create new file (fails if exists)

Quick Check: What mode should you use to overwrite an existing file? (Answer: 'w' mode)

The with Statement

6

Safe and Efficient File Handling

# The with statement automatically handles file closing

# Without 'with' (manual closing)
file = open("manual.txt", "w")
file.write("Hello")
file.close()  # Must remember to close!

# With 'with' (automatic closing)
with open("auto.txt", "w") as file:
    file.write("Hello")
# File is automatically closed here

# Multiple files with 'with'
with open("file1.txt", "w") as f1, open("file2.txt", "w") as f2:
    f1.write("Content of file 1")
    f2.write("Content of file 2")

# Reading and writing in the same with block
with open("source.txt", "r") as source, open("dest.txt", "w") as dest:
    content = source.read()
    dest.write(content.upper())

# Using with for binary files
with open("image.jpg", "rb") as file:
    data = file.read()
    # Process binary data

# Why use 'with':
# 1. Automatic closing — no need to call close()
# 2. Exception safe — file closes even if error occurs
# 3. Cleaner code — less boilerplate
# 4. Resource management — ensures proper cleanup

# Equivalent without 'with' (more code):
try:
    file = open("example.txt", "w")
    file.write("Hello")
except Exception as e:
    print(f"Error: {e}")
finally:
    file.close()
# with does all this automatically!

Why use 'with':

  • Automatic closing — no need to call close()
  • Exception safe — closes even on errors
  • Cleaner code — less boilerplate
  • Resource management — ensures proper cleanup

Quick Check: What is the main advantage of using 'with' for file handling? (Answer: Automatic file closing)

Error Handling with Files

7

Handling File-Related Errors

# Common file handling errors and how to handle them

# 1. FileNotFoundError
try:
    with open("nonexistent.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("The file doesn't exist!")

# 2. PermissionError
try:
    with open("/protected/file.txt", "w") as file:
        file.write("Hello")
except PermissionError:
    print("You don't have permission to write to this file!")

# 3. IsADirectoryError
try:
    with open("/home/user", "r") as file:
        content = file.read()
except IsADirectoryError:
    print("Cannot open a directory as a file!")

# 4. UnicodeDecodeError (reading binary as text)
try:
    with open("image.jpg", "r") as file:
        content = file.read()
except UnicodeDecodeError:
    print("File contains binary data! Use 'rb' mode.")

# 5. General Exception handling
try:
    with open("somefile.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("File not found.")
except PermissionError:
    print("Permission denied.")
except Exception as e:
    print(f"Unexpected error: {e}")

# 6. Using os.path to check before opening
import os

filename = "data.txt"
if os.path.exists(filename):
    with open(filename, "r") as file:
        content = file.read()
else:
    print(f"'{filename}' does not exist.")

# 7. os.path checks
if os.path.isfile("myfile.txt"):
    print("It's a regular file")
if os.path.isdir("myfolder"):
    print("It's a directory")
if os.access("myfile.txt", os.R_OK):
    print("File is readable")
if os.access("myfile.txt", os.W_OK):
    print("File is writable")

Common file errors:

  • FileNotFoundError — file doesn't exist
  • PermissionError — don't have permission
  • IsADirectoryError — trying to open a directory
  • UnicodeDecodeError — wrong encoding
  • Always handle errors — robust programs handle exceptions

Quick Check: What exception is raised when a file doesn't exist? (Answer: FileNotFoundError)

Try It Yourself

Experiment with file handling in the editor below. Try reading, writing, and managing files.

Loading Pyodide... 0%
Python Code Editor
========================================
FILE HANDLING INTRODUCTION PRACTICE
========================================

1. WRITING TO A FILE
File 'my_file.txt' created and written!

2. READING FROM A FILE
File content:
Hello, World!
This is line 2
This is line 3

3. READING LINE BY LINE
Line: Hello, World!
Line: This is line 2
Line: This is line 3

4. APPENDING TO A FILE
Appended new line!

5. READING UPDATED FILE
Hello, World!
This is line 2
This is line 3
This line was appended

6. USING READLINES()
Number of lines: 4
Line 1: Hello, World!
Line 2: This is line 2
Line 3: This is line 3
Line 4: This line was appended

File handling introduction practice complete!
🏆

You've Got It!

You now understand the fundamentals of file handling in Python. You know how to open, read, write, and manage files safely and efficiently.

Quick Quiz

Test what you've learned:

1. What does the 'r' mode mean when opening a file?
2. What is the main advantage of using 'with' for file handling?
3. Which method reads the entire file as a string?
4. What mode should you use to add content to the end of a file?
5. What exception is raised when a file doesn't exist?

Frequently Asked Questions

What is file handling in Python? ▼

File handling is the process of working with files in Python — creating, opening, reading, writing, and closing files. It allows programs to store and retrieve data permanently.

Why should I use 'with' when working with files? ▼

The 'with' statement automatically closes files, even if an error occurs. It makes your code cleaner, safer, and more readable. Without 'with', you need to manually call close() and handle exceptions.

What is the difference between 'r', 'w', and 'a' modes? ▼

'r' — read mode (file must exist). 'w' — write mode (creates new file or overwrites). 'a' — append mode (adds to the end of file, creates if doesn't exist).

What's a common interview question about file handling? ▼

Common questions include: "How do you read and write files in Python?" "What is the purpose of the with statement?" and "Explain different file modes in Python."

How do I handle file-related errors? ▼

Use try-except blocks to catch specific exceptions like FileNotFoundError, PermissionError, and IsADirectoryError. You can also use os.path methods to check if a file exists before opening.

What happens if I forget to close a file? ▼

If you forget to close a file, the file stays open, wasting system resources. In large programs, this can lead to "too many open files" errors. The with statement prevents this by automatically closing files.

Where to Go From Here

Now that you understand file handling basics, check out these related topics:

Create File

Learn different ways to create files in Python.

Learn More →

Read Files

Master reading files with different methods.

Learn More →

Write to File

Learn how to write data to files effectively.

Learn More →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
Previous: 📝 Module Assignments Next: Create File →