Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
📖 File Fundamentals📖 Reading Files Effectively✍️ Writing Files Correctly🗂️ Working with File Paths🤝 Context Managers & Safety📊 CSV Data Processing🔄 JSON Parsing & Serialization🔐 Binary Files & Encoding⚙️ Performance & Best Practices
Python/File Io/Opening Closing Files

📖 File Fundamentals — Opening and Closing Files

Learn the basics of working with files: opening them, reading/writing data, and closing them properly.


🎯 Opening Files

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:

  • `"r"` — Read (default, file must exist)
  • `"w"` — Write (creates new or overwrites existing)
  • `"a"` — Append (adds to end of file)
  • `"x"` — Create (fails if file exists)
  • `"b"` — Binary mode (combine with others: `"rb"`, `"wb"`)

💡 Why Closing Matters

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!

🎨 Real-World Example: Reading a Log File

# 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()

📊 File Object Operations

MethodPurposeExample
`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()`

🔑 Key Takeaways

  • ✅ Use `open(filename, mode)` to open files
  • ✅ Modes: `"r"` read, `"w"` write, `"a"` append
  • ✅ Always `close()` files after use
  • ✅ Closing releases resources and saves data
  • ✅ File must exist for `"r"` mode

Ready to practice? Challenges | Quiz


Resources

Python Docs

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

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn