How to Read and Write Files in Python
File handling is a fundamental concept in Python that lets you work with files on your computer—be it reading configuration files, logs, or saving user data. Python’s open()
function, along with methods like read()
, write()
, and the with
statement, provides an easy-to-use and safe interface for working with files. This article shows you the standard approaches, key patterns, and best practices for reading and writing files in Python.
Table of Content
Why Work with Files in Python?
- Persistence: Store data so it’s available between program runs.
- Data Exchange: Read configuration, save results, or share data with other programs.
- Logging: Keep a record of program actions or errors.
- Automation: Batch process files for data cleaning, reporting, etc.
Syntax & Structure
# Open a file
file_obj = open("filename.txt", "mode")
# ... read or write using file_obj
file_obj.close()
# Recommended: Use with statement (auto-closes the file)
with open("filename.txt", "mode") as file_obj:
# read or write using file_obj
open(filename, mode)
: Opens a file; returns a file object.filename
: Name (and path) of the file to open.mode
:'r'
(read),'w'
(write),'a'
(append),'b'
(binary),'x'
(exclusive create),'t'
(text, default).- Always call
close()
or use thewith
statement, which does this for you.
Basic Examples: Reading Files
1. Read Entire File as String
with open("example.txt", "r") as file:
content = file.read()
print(content)
2. Read File Line by Line
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
3. Read File into a List of Lines
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines)
Writing to Files
1. Write Text to a File (Overwrites Existing Content or Creates New)
with open("output.txt", "w") as file:
file.write("Hello, world!\n")
2. Append to an Existing File
with open("output.txt", "a") as file:
file.write("Adding another line.\n")
3. Write a List of Lines
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("lines.txt", "w") as file:
file.writelines(lines)
File Modes Explained
Mode | Description | Best For |
---|---|---|
'r' |
Read text file (default mode) | Reading existing files |
'w' |
Write (overwrites file or creates new) | Start new file or replace old |
'a' |
Append (creates file if not exists) | Adding logs, new lines |
'b' |
Binary mode (add to other mode: e.g. 'rb' , 'wb' ) |
Images, non-text data |
'x' |
Create file, fail if file already exists | One-time writes, exclusive output |
't' |
Text mode (default if omitted) | Regular text file work |
Comparison Table: File Reading & Writing Patterns
Pattern | Example Code | Best For |
---|---|---|
Read full file as string |
|
Small text/config files |
Process file line-by-line |
|
Large files, parsing logs |
Write output (overwrite) |
|
Reports, config outputs |
Append output |
|
Logging, adding to files |
Binary read |
|
Images, PDF, binary data |
Useful Tips
- Use
with
: Always use thewith
statement. Automatically closes files, even if there’s an error. - Be explicit: Specify the correct
mode
('r'
,'w'
,'a'
,'b'
) for your purpose. - Don’t read large files at once: For big files, process line by line to save memory.
- Handle errors: Use
try
/except
to catch file not found, permission errors, etc. - Writing lists: Add
\n
at the end of each line if usingwritelines()
. - Path management: For cross-platform code, use
os.path
orpathlib
to build file paths.
Conclusion
Python’s file handling is simple and powerful. Just remember to use the with
statement, pick the right mode for your task, and process files efficiently for your use case. These examples and patterns will help you reliably manage files in scripts, applications, or data processing pipelines.
Comments
Post a Comment