Quest 2 β’ Lesson 1
π File I/O (Read & Write)
Learn how to read from and write to files β essential for realβworld Python applications.
File I/O (Input/Output) allows your Python programs to work with files on disk. You can read data from files, write data to files, and append to existing files.
"The
with statement automatically closes the file for you β preventing memory leaks and corruption."
π Live Demo
Simulate writing to and reading from a file.
File content will appear here.
π§ Writing to a File
with open("data.txt", "w") as file:
file.write("Hello, world!")
file.write("Hello, world!")
open("filename", "mode")β opens a file."w"β write mode (overwrites existing).withβ ensures the file is closed properly.
π Reading from a File
with open("data.txt", "r") as file:
content = file.read()
print(content)
content = file.read()
print(content)
"r"β read mode (default)..read()β reads the entire file as a string..readlines()β reads line by line as a list.
π File Modes
"r" β read (default)"w" β write (overwrites)"a" β append (adds to end)"r+" β read and write"rb" β read binary"wb" β write binary
file_io.py
# Write to a file
with open("notes.txt", "w") as f:
f.write("Python is awesome!\n")
f.write("I'm learning file I/O.")
# Read from a file
with open("notes.txt", "r") as f:
content = f.read()
print(content)
with open("notes.txt", "w") as f:
f.write("Python is awesome!\n")
f.write("I'm learning file I/O.")
# Read from a file
with open("notes.txt", "r") as f:
content = f.read()
print(content)
β¨ Challenge: Write a Log File
Write a program that:
- Asks the user for their name.
- Writes
"User: {name} visited at {current_time}"to a log file. - Uses the
datetimemodule for timestamps.
from datetime import datetime
name = input("Enter your name: ")
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open("log.txt", "a") as f:
f.write(f"User: {name} visited at {timestamp}\n")
print("Visit logged!")
name = input("Enter your name: ")
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open("log.txt", "a") as f:
f.write(f"User: {name} visited at {timestamp}\n")
print("Visit logged!")
β‘οΈ Next Lesson
Lesson 2.2: Modules & Packages β organise and reuse code.
Continue to Lesson 2.2 β(Coming soon β check back or buy Pro Pack for early access)
β€οΈ Support Free Education
This course is 100% free. If it helps you, consider buying me a coffee.
β Buy Me a Coffee