- Learning Objectives
- Prerequisites
- Introduction
- Opening a File
- The open() Function
- Syntax
- Parameters of open()
- File Modes
- Reading Methods
- Writing Methods
- The with Statement
- Internal Working
- Summary
After completing this chapter, you will be able to:
- Open files using the open() function.
- Read file contents using different methods.
- Write data into files.
- Understand file modes.
- Use the with statement.
- Handle files safely.
Before learning this chapter, you should know:
- File Handling Basics
- Strings
- Variables
- Functions
- Exception Handling
Before reading or writing data,
a file must first be opened.
Python provides the built-in
open()function to access files.
After opening a file,
we can
- Read data
- Write data
- Append data
- Close the file
The first step in File Handling is opening the file.
Python uses
open()to create a connection between the program and the file.
The open() function opens a file and returns a file object.
The returned file object is used to perform all file operations.
open(file_name, mode)Specifies the name or path of the file.
Example
"student.txt"Specifies how the file will be opened.
Examples
r
w
a
x
| Mode | Description |
|---|---|
r |
Read existing file (default) |
w |
Write (creates new file or overwrites existing file) |
a |
Append data to the end of an existing file |
x |
Create a new file. Raises an error if the file already exists |
r+ |
Read and write |
w+ |
Read and write (overwrites existing content) |
a+ |
Read and append |
rb |
Read binary file |
wb |
Write binary file |
ab |
Append binary file |
Python provides several methods for reading data.
Reads the entire file or a specified number of characters.
Example
file = open("student.txt","r")
print(file.read())
file.close()Reads one line at a time.
Example
file = open("student.txt","r")
print(file.readline())
file.close()Reads all lines and returns a list.
Example
file = open("student.txt","r")
print(file.readlines())
file.close()Writes a string into the file.
Example
file = open("student.txt","w")
file.write("Hello Python")
file.close()Writes multiple lines.
Example
file = open("student.txt","w")
file.writelines([
"Java\n",
"Python\n",
"SQL\n"
])
file.close()Instead of writing
file = open(...)
...
file.close()Python recommends
with open("student.txt","r") as file:
print(file.read())Advantages
- Automatically closes the file.
- Cleaner code.
- Better exception handling.
- Prevents resource leaks.
Program Starts
↓
open()
↓
Operating System Opens File
↓
File Object Created
↓
Read / Write Operation
↓
close()
↓
Program Ends
- Easy file access.
- Supports different file modes.
- Safe resource management using
with. - Supports both text and binary files.
- Always use the
withstatement when possible. - Open files in the correct mode.
- Close files after use if not using
with. - Handle file-related exceptions.
- Use descriptive file names.
Opening a non-existent file in read mode.
Raises
FileNotFoundErrorUsing write mode unintentionally.
w deletes existing content before writing.
Forgetting to close files when not using with.
Trying to read from a file opened in write mode.
file = open("student.txt", "r")
print(file)
file.close()<_io.TextIOWrapper ...>
file = open("student.txt", "r")
print(file.read())
file.close()Welcome to Python
File Handling Example
file = open("student.txt", "r")
print(file.readline())
file.close()Welcome to Python
file = open("student.txt", "r")
print(file.readlines())
file.close()['Welcome to Python\n', 'File Handling Example']
file = open("student.txt", "w")
file.write("Python Programming")
file.close()Creates the file if it does not exist.
If it exists,
its previous content is overwritten.
file = open("student.txt", "a")
file.write("\nAdvanced Python")
file.close()Adds data to the end of the file without removing existing content.
file = open("courses.txt", "w")
file.writelines([
"Java\n",
"Python\n",
"SQL\n"
])
file.close()with open("student.txt", "r") as file:
print(file.read())The file is automatically closed after the block finishes.
file = open("newfile.txt", "x")
file.write("New File Created")
file.close()Raises
FileExistsErrorif the file already exists.
file = open("student.txt", "r")
print(file.read(10))
file.close()Welcome t
Program Starts
↓
open()
↓
File Object Created
↓
Read / Write Method
↓
Data Processed
↓
close()
↓
Program Ends
Python Program
│
├── File Object
│ │
│ ├── read()
│ ├── write()
│ ├── readline()
│ └── close()
│
└── student.txt
It opens a file and returns a file object.
r(Read Mode)
read()reads the entire file or a specified number of characters.readline()reads one line at a time.
A list containing all lines in the file.
write()writes a single string.writelines()writes multiple strings from an iterable. It does not automatically add newline characters.
It automatically closes the file after the block finishes, even if an exception occurs.
If the file exists, its contents are overwritten.
If it does not exist, a new file is created.
axFileNotFoundError- Read the complete contents of a file.
- Read one line at a time.
- Read only the first 20 characters.
- Write student details to a file.
- Append new records to an existing file.
- Create a new file using
xmode. - Read a file using the
withstatement.
open()→ Opens a file.read()→ Reads complete file or specified characters.readline()→ Reads one line.readlines()→ Returns a list of lines.write()→ Writes one string.writelines()→ Writes multiple strings.with→ Automatically closes the file.r→ Readw→ Writea→ Appendx→ Create
In this chapter, you learned:
- open() Function
- File Modes
- Reading Methods
- Writing Methods
- The with Statement
- Practical Programs
- Best Practices
- Common Mistakes
- Interview Questions
- Practice Programs
- Quick Revision