File I/O in Python: Read and Write Data Like a Script
Working with files is a key skill when you want Python to automate real tasks like reports, logs, or data exchange.
What you'll learn
- write text files
- read text files
- process file contents line by line
Example
filename = "example_data.txt"
with open(filename, "w", encoding="utf-8") as file:
file.write("name,score\n")
file.write("Ayla,88\n")
with open(filename, "r", encoding="utf-8") as file:
lines = file.readlines()
Real-world use
Python can generate CSV data, create logs for automation, or import data from text reports.
Why it matters
Once you can read and write files, you can build scripts that interact with external data sources instead of only working in memory.
Next
Use file I/O with exceptions to handle missing or invalid files safely.
Top comments (0)