Python allows programs to work with files stored on the system so that information can be saved permanently. This is important because data stored in variables exists only as long as the program is running. File handling makes it possible to store logs, configuration data, user-generated content, and processing results in a structured way. Python makes file handling simple through its built-in open() function and related methods.
The following text file will be used in all examples:
Hello Python!
Welcome to File Handling.
This is line 3.
Before performing any operations, a file must be opened using the open() function. The function takes two values: the name of the file and the mode. The mode determines what type of operation will happen on the file. Since opening a file is the starting point of file handling, choosing the right mode is very important because it decides whether the content will be read, overwritten, or appended.
f = open("sample.txt", "r")
The above line opens the file for reading.
Different modes provide different behavior while working with files. Reading mode opens the file only for reading. Write mode creates a new file or erases an existing one before writing. Append mode adds new content without removing old data. The create mode makes sure the file must not already exist. Combined modes like r+, w+, and a+ allow both reading and writing depending on what the program requires.
| Mode | Meaning | Use Case |
|---|---|---|
| r | Read only | Reading file content |
| w | Write | Overwrite file or create new |
| a | Append | Add new lines at end |
| x | Create | Error if file exists |
| r+ | Read + Write | Modify existing content |
| w+ | Write + Read | Overwrite, then read |
| a+ | Append + Read | Append and read |
Reading allows a program to access stored content. Python provides several methods depending on how much of the file needs to be read at a time. Full reading is suitable for small text files, while line-by-line reading is useful for logs or large datasets. The method you choose affects performance and memory usage.
This method loads the whole content of the file as a single string. It is ideal for smaller files or when you want to display or process everything together.
f = open("sample.txt", "r")
print(f.read())
Hello Python!
Welcome to File Handling.
This is line 3.
This reads the complete file from start to end.
This method reads only the next line from the file. It is ideal when reading input gradually or processing logs one line at a time.
f = open("sample.txt", "r")
print(f.readline())
Hello Python!
Each call to readline() moves the cursor forward.
This method returns every line of the file as a separate list element. It is useful when you want to iterate through lines using a loop.
f = open("sample.txt", "r")
print(f.readlines())
['Hello Python!\n', 'Welcome to File Handling.\n', 'This is line 3.\n']
This gives a list where each element represents one line.
Writing allows programs to save data permanently. Depending on the mode, writing may overwrite existing content or add new lines at the end. Write operations are common in reporting, logging, and saving results.
We will use output.txt for writing examples.
When a file is opened in write mode, old content is erased. The write() method then stores new text inside the file.
f = open("output.txt", "w")
f.write("Python file writing example.")
Python file writing example.
This creates or overwrites the file.
Opening a file with "w" always removes old content before adding new text.
f = open("output.txt", "w")
f.write("This replaces old content.")
This replaces old content.
The previous content is deleted and replaced.
Appending adds new data to the bottom of the file. Existing content remains untouched.
f = open("output.txt", "a")
f.write("\nAppended line.")
This replaces old content. Appended line.
Appending is ideal for maintaining logs or continuous entries.
When a file is opened using open(), it must be closed manually. Closing a file releases system resources and ensures that all written data is properly saved. Forgetting to close a file may lead to memory leaks or file corruption.
f = open("sample.txt", "r")
print(f.read())
f.close()
Closing completes the file operation safely.
Using a with block makes file handling safer because Python automatically closes the file after the block ends. This prevents accidental errors and is considered the best practice.
with open("sample.txt", "r") as f:
print(f.read())
Hello Python!
Welcome to File Handling.
This is line 3.
Python closes the file automatically after printing.
Python offers helpful methods to control the cursor and access information about the file.
| Method | Description |
|---|---|
| read() | Read entire file |
| readline() | Read one line |
| readlines() | Read all lines |
| write() | Write text |
| tell() | Show cursor position |
| seek(pos) | Move cursor |
| close() | Close file |
The tell() method reveals where the cursor is located, and seek() moves the cursor to a certain position. This is useful when reading or rewriting specific parts of a file.
f = open("sample.txt", "r")
print(f.tell())
f.seek(0)
print(f.readline())
0
Hello Python!
Here, the cursor resets to the beginning before reading the first line.
The os module helps manage files and folders. It can show the current directory, create new directories, and remove files.
import os
print(os.getcwd())
os.mkdir("new_folder")
os.remove("old.txt")
This allows file organization and system-level operations through Python.
Sometimes a file may not exist or may not be accessible. Instead of crashing, your program can handle such errors using a try-except block. This helps in building stable and user-friendly applications.
try:
f = open("unknown.txt", "r")
print(f.read())
except FileNotFoundError:
print("File does not exist!")
File does not exist!
The program continues running instead of stopping abruptly.
The mode "w+" allows writing first and then reading. The cursor must be moved back to the beginning using seek() after writing.
with open("sample_write.txt", "w+") as f:
f.write("Hello World")
f.seek(0)
print(f.read())
Hello World
This mode is useful when both writing and verification are needed in the same operation.