File Input and Output (I/O) in Python
In Python, file I/O is used to read from or write to files. This is an essential part of any programming language when it comes to data processing, logging, or configuration.
Opening Filesโ
To work with files in Python, you use the built-in open() function.
file = open("example.txt", "r") # Open for reading
Modes:โ
| Mode | Description |
|---|---|
'r' | Read (default). Fails if the file doesnโt exist. |
'w' | Write. Creates a new file or truncates existing one. |
'a' | Append. Adds content to the end of the file. |
'b' | Binary mode. Used with 'rb', 'wb', etc. |
'x' | Create. Fails if the file already exists. |
Reading from a Fileโ
read() โ Reads entire contentโ
with open("example.txt", "r") as file:
content = file.read()
print(content)
readline() โ Reads one line at a timeโ
with open("example.txt", "r") as file:
line = file.readline()
print(line)
readlines() โ Reads all lines into a listโ
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines)
Writing to a Fileโ
write() โ Write string to fileโ
with open("output.txt", "w") as file:
file.write("Hello, world!")
writelines() โ Write list of stringsโ
lines = ["Line 1\n", "Line 2\n"]
with open("output.txt", "w") as file:
file.writelines(lines)
Using with Statement (Best Practice)โ
The with block ensures the file is automatically closed after use:
with open("data.txt", "r") as file:
data = file.read()
This is the recommended way to handle files in Python.
Error Handling in File I/Oโ
Always handle file operations with care to avoid exceptions:
try:
with open("config.txt", "r") as file:
config = file.read()
except FileNotFoundError:
print("File not found.")
except IOError:
print("Error while handling the file.")
File Pathsโ
You can also handle file paths using the os or pathlib module:
from pathlib import Path
file_path = Path("docs") / "myfile.txt"
with open(file_path, "r") as file:
print(file.read())
Example: Reading & Writingโ
# Write to a file
with open("sample.txt", "w") as file:
file.write("This is a test.")
# Read the file
with open("sample.txt", "r") as file:
print(file.read())
Summaryโ
- Use
open()to access files. - Use
read(),readline(), orreadlines()to read. - Use
write()orwritelines()to write. - Always use
withto handle files safely. - Handle exceptions for robustness.