File I/O
Python provides built-in functions to read and write files. Files are a fundamental way to persist data beyond the program's execution. The `open()` function returns a file object, and you can use methods like `read()`, `write()`, and `close()`. The `with` statement is recommended for automatic resource management.
Opening and Closing Files
Use `open(filename, mode)`. Modes include `'r'` (read, default), `'w'` (write, overwrites), `'a'` (append), `'x'` (exclusive creation), and `'+'` for updating. Binary files use `'rb'`, `'wb'`, etc.
file = open("data.txt", "r")
content = file.read()
file.close()
Using `with` Statement
The `with` block ensures the file is closed automatically, even if an error occurs.
with open("data.txt", "r") as file:
content = file.read()
# file is automatically closed here
Reading Methods
- `read()` – entire file as a string.
- `readline()` – reads one line at a time.
- `readlines()` – returns a list of lines.
with open("data.txt", "r") as file:
for line in file:
print(line.strip())
Writing to Files
Use `write()` or `writelines()`. Write mode `'w'` creates/overwrites; append mode `'a'` adds to the end.
with open("output.txt", "w") as file:
file.write("Hello, Python!n")
file.writelines(["Line 1n", "Line 2n"])
Two Minute Drill
- Use `open()` to open files; always close with `.close()` or use `with`.
- Modes: `'r'`, `'w'`, `'a'`, `'rb'`, `'wb'`, etc.
- `with` statement ensures automatic closure.
- Read with `read()`, `readline()`, or iterate over the file object.
- Write with `write()` or `writelines()`.
Need more clarification?
Drop us an email at career@quipoinfotech.com
