Python File Handling
File handling is an indispensable part of any programming language. Python provides simple yet powerful built-in functionality for creating, reading, and writing files.
Opening Files: open()
To operate on a file, you must first open it using the open() function. The open() function returns a file object.
Basic syntax:file_object = open(file_name, mode)
file_name: The path to the file you want to open.mode: A string specifying how you intend to operate on the file.
File Modes (Mode)
| Mode | Description |
|---|---|
'r' | Read - Default mode. If the file doesn't exist, it raises FileNotFoundError. |
'w' | Write - Opens the file for writing. If the file exists, its contents are cleared; if it doesn't exist, a new file is created. |
'a' | Append - Opens the file for writing, but new content is appended to the end of the file rather than clearing existing content. If the file doesn't exist, a new file is created. |
'r+' | Read/Write - Opens the file for both reading and writing. |
'b' | Binary Mode - Can be combined with r, w, a (e.g., 'rb', 'wb') for handling non-text files (e.g., images, audio). |
't' | Text Mode - Default mode. Can be combined with r, w, a. |
Using with Statement
When handling files, best practice is to use the with statement. The with statement ensures that after the code block finishes execution, the file is properly closed even if an error occurs.
with open('example.txt', 'w') as f:
f.write('Hello, World!\n')
f.write('This is a new line.\n')
# When the `with` code block ends, file f is automatically closed.Reading Files
There are several methods for reading content from a file.
Suppose we have a file example.txt with the following content:
Hello, World!
This is a new line.
And another one.file.read()
Reads all contents of the file and returns them as a single string.
with open('example.txt', 'r') as f:
content = f.read()
print(content)file.readline()
Reads only one line from the file at a time (including the newline character \n at the end) and returns it as a string.
with open('example.txt', 'r') as f:
line1 = f.readline()
line2 = f.readline()
print(f"Line 1: {line1.strip()}") # .strip() removes leading/trailing whitespace
print(f"Line 2: {line2.strip()}")file.readlines()
Reads all lines from the file and returns them as a list of strings. Each string in the list represents one line from the file.
with open('example.txt', 'r') as f:
lines = f.readlines()
print(lines)
# Output: ['Hello, World!\n', 'This is a new line.\n', 'And another one.\n']Directly Iterating Over File Object
This is the most common and efficient way to read a file line by line, as it doesn't load all lines into memory at once.
with open('example.txt', 'r') as f:
for line in f:
print(line.strip()) # strip() removes newline charactersWriting to Files
file.write(string)
Writes a string to the file. This method does not automatically add newline characters; you need to manually add \n.
with open('output.txt', 'w') as f:
f.write('First line.\n')
f.write('Second line.\n')file.writelines(list_of_strings)
Writes a list of strings to the file. Similarly, it does not automatically add newline characters.
lines_to_write = ['Header\n', 'Data line 1\n', 'Data line 2\n']
with open('data.txt', 'w') as f:
f.writelines(lines_to_write)