🗃️ Python File Handling

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.

📄 Sample File

The following text file will be used in all examples:

sample.txt

Hello Python!
Welcome to File Handling.
This is line 3.

1. Opening a File

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.

Code:

f = open("sample.txt", "r")

The above line opens the file for reading.

2. File Modes (with Use Cases)

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 Table:

ModeMeaningUse Case
rRead onlyReading file content
wWriteOverwrite file or create new
aAppendAdd new lines at end
x                 Create                         Error if file exists
r+Read + Write              Modify existing content
w+Write + ReadOverwrite, then read
a+Append + ReadAppend and read

3. Reading Files

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.

a) read() – Reads the Entire File

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.

Code:

f = open("sample.txt", "r")
print(f.read())

Output:

Hello Python!
Welcome to File Handling.
This is line 3.

This reads the complete file from start to end.

b) readline() – Reads One Line

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.

Code:

f = open("sample.txt", "r")
print(f.readline())

Output:

Hello Python!

Each call to readline() moves the cursor forward.

c) readlines() – Reads All Lines as List

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.

Code:

f = open("sample.txt", "r")
print(f.readlines())

Output:

['Hello Python!\n', 'Welcome to File Handling.\n', 'This is line 3.\n']

This gives a list where each element represents one line.

4. Writing Files

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.

a. write() – Write text to a file

When a file is opened in write mode, old content is erased. The write() method then stores new text inside the file.

Code:

f = open("output.txt", "w")
f.write("Python file writing example.")

Output inside output.txt:

Python file writing example.

This creates or overwrites the file.

b. "w" Mode – Write (Overwrites existing file)

Opening a file with "w" always removes old content before adding new text.

Code:

f = open("output.txt", "w")
f.write("This replaces old content.")

Output inside output.txt:

This replaces old content.

The previous content is deleted and replaced.

c. "a" Mode – Append (Write at the end of a file)

Appending adds new data to the bottom of the file. Existing content remains untouched.

Code:

f = open("output.txt", "a")
f.write("\nAppended line.")

Output inside output.txt:

This replaces old content. Appended line.

Appending is ideal for maintaining logs or continuous entries.

5. Closing a File

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.

Code:

f = open("sample.txt", "r")
print(f.read())
f.close()

Closing completes the file operation safely.

6. Using with Statement (Automatic Closing)

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.

Code:

with open("sample.txt", "r") as f:
   print(f.read())

Output:

Hello Python!
Welcome to File Handling.
This is line 3.

Python closes the file automatically after printing.

7. File Object Methods

Python offers helpful methods to control the cursor and access information about the file.

MethodDescription
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

Using seek() and tell()

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.

Code:

f = open("sample.txt", "r")
print(f.tell())
f.seek(0)
print(f.readline())

Output:

0
Hello Python!

Here, the cursor resets to the beginning before reading the first line.

8. Working with Files and Directories (os Module)

The os module helps manage files and folders. It can show the current directory, create new directories, and remove files.

Code:

import os

print(os.getcwd())
os.mkdir("new_folder")
os.remove("old.txt")

This allows file organization and system-level operations through Python.

9. Exception Handling in File Operations

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.

Code:

try:
   f = open("unknown.txt", "r")
   print(f.read())
except FileNotFoundError:
   print("File does not exist!")

Output:

File does not exist!

The program continues running instead of stopping abruptly.

10. Writing and Reading in Same File

The mode "w+" allows writing first and then reading. The cursor must be moved back to the beginning using seek() after writing.

Code:

with open("sample_write.txt", "w+") as f:
   f.write("Hello World")
   f.seek(0)
   print(f.read())

Output:

Hello World

This mode is useful when both writing and verification are needed in the same operation.