
Python
Learn the basics of working with files: opening them, reading/writing data, and closing them properly.
Use the `open()` function to work with files. It requires a filename and mode.
# Open a file for reading (default mode)
file = open("data.txt", "r")
# Do something with the file
content = file.read()
# Always close the file
file.close()File Modes:
Closing files releases system resources and ensures all data is saved.
# Open for writing
file = open("output.txt", "w")
file.write("Hello, World!")
file.close() # Must close to save data!
# Without close, file might not be fully written
file = open("output.txt", "w")
file.write("Hello")
# File not closed - data might be lost!# Open a log file for reading
log_file = open("application.log", "r")
# Read entire file as string
content = log_file.read()
print(content)
# Close when done
log_file.close()| Method | Purpose | Example |
|---|---|---|
| `read()` | Read entire file | `content = file.read()` |
| `readline()` | Read one line | `line = file.readline()` |
| `readlines()` | Read all lines as list | `lines = file.readlines()` |
| `write(text)` | Write text | `file.write("Hello")` |
| `close()` | Close file | `file.close()` |
Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward