Introduction to File Handling
File handling is a crucial part of any programming language. It allows a program to
read data from and write data to a file on the disk. This enables data persistence,
meaning the data exists even after the program has finished running. In Python, file
handling is straightforward, with built-in functions and methods to create, open, read,
write, and manipulate files.
1. Opening and Closing Files
Before you can read from or write to a file, you must first open it. Python provides the
built-in open() function for this purpose.
The open() Function
The open() function takes the file path and the mode as its primary arguments and
returns a file object (also called a file handle).
Syntax:
file_object = open("filename", "mode")
● filename: A string containing the name or path of the file.
● mode: A string that specifies the purpose for which the file is being opened (e.g.,
reading, writing).
# Opening a file for reading
file = open("example.txt", "r")
# It is crucial to close the file after you're done with it
file.close()
Failing to close a file can lead to resource leaks and may prevent other programs from
accessing the file.
The with Statement (Recommended)
The modern and recommended way to handle files is using the with statement. It
ensures that the file is automatically closed when the block of code inside the with
statement is exited, even if errors occur.
Syntax:
with open("filename", "mode") as file_object:
# Perform file operations here
# Using the with statement to open a file
with open("example.txt", "r") as file:
content = file.read()
print(content)
# The file is automatically closed here, no need for file.close()
2. File Modes
The mode in which you open a file determines what operations you can perform on it.
Modes are specified as strings.
Main Modes
Mode Description Action if File Exists Action if File
Doesn't Exist
'r' Read (Default). Reads from start FileNotFoundError
Opens for reading.
The file pointer is at
the beginning.
'w' Write. Opens for Erases all content, Creates a new file
writing. writes from start
'a' Append. Opens for Appends to the end Creates a new file
writing. The file
pointer is at the end
of the file.
'x' Exclusive Creation. FileExistsError Creates a new file
Creates a new file
and opens it for
writing.
Secondary Modifiers
These can be combined with the main modes.
Modifier Description
'b' Binary Mode. For handling non-text files like
images, audio, etc. (e.g., 'rb', 'wb').
't' Text Mode (Default). For handling text files.
'+' Update Mode. Opens a file for both reading
and writing (updating). (e.g., 'r+', 'w+', 'a+').
Combined Modes Table
Mode Description
'r+' Read and write. Pointer at the beginning.
'w+' Write and read. Erases existing file content.
'a+' Append and read. Pointer at the end for writing.
'rb' Read in binary mode.
'wb' Write in binary mode.
'ab' Append in binary mode.
3. Reading and Writing Files
Once a file is open, you can read from or write to it using the methods of the file
object.
Reading from a File
To read from a file, you must open it in a read mode ('r', 'r+').
Method Description Use Case
.read(size) Reads the entire file content Small files where the entire
as a single string. If size is content can fit in memory.
specified, it reads that many
characters/bytes.
.readline() Reads a single line from the Processing a file line by line.
file, including the newline
character (\n).
.readlines() Reads all lines from the file Small files; can be
and returns them as a list of memory-intensive for large
strings. files.
for line in file: The most memory-efficient The standard and preferred
way to read a file line by line. method for large files.
Example:
with open("sample.txt", "w") as f:
f.write("First line.\n")
f.write("Second line.\n")
f.write("Third line.\n")
with open("sample.txt", "r") as file:
# Using .read()
print("--- Using .read() ---")
content = file.read()
print(content)
with open("sample.txt", "r") as file:
# Using .readline()
print("\n--- Using .readline() ---")
line1 = file.readline()
print(line1.strip()) # .strip() removes leading/trailing whitespace, including '\n'
line2 = file.readline()
print(line2.strip())
with open("sample.txt", "r") as file:
# Using .readlines()
print("\n--- Using .readlines() ---")
lines_list = file.readlines()
print(lines_list) # Output: ['First line.\n', 'Second line.\n', 'Third line.\n']
with open("sample.txt", "r") as file:
# Using a for loop (best practice)
print("\n--- Using a for loop ---")
for line in file:
print(line.strip())
Writing to a File
To write to a file, you must open it in a write or append mode ('w', 'a', 'w+', 'a+').
Method Description
.write(string) Writes the given string to the file. It does not
add a newline character automatically.
.writelines(list_of_strings) Writes a list of strings to the file. It does not
add newline characters between the strings.
Example:
lines_to_write = ["This is a new line.\n", "And another one.\n"]
# Using 'w' to overwrite the file
with open("output.txt", "w") as file:
file.write("This file has been overwritten.\n")
file.writelines(lines_to_write)
# Using 'a' to append to the file
with open("output.txt", "a") as file:
file.write("This line was appended.\n")
# Reading the final content
with open("output.txt", "r") as file:
print("\n--- Final Content of output.txt ---")
print(file.read())