Become the go-to AI expert in 30 days
AI keeps coming up at work, but you still don't get it?
That's exactly why 1M+ professionals working at Google, Meta, and OpenAI read Superhuman AI daily.
Here's what you get:
Daily AI news that matters for your career - Filtered from 1000s of sources so you know what affects your industry.
Step-by-step tutorials you can use immediately - Real prompts and workflows that solve actual business problems.
New AI tools tested and reviewed - We try everything to deliver tools that drive real results.
All in just 3 minutes a day

Knowing how to read and write files is one of the most essential parts of programming, as it allows us to move information around in whatever system we build. Thankfully, Python makes it really easy to write I/O logic.
Basic Python File I/O
Before reaching for library-specific I/O, it’s important to see what Python can do on its own. The built-in open() function is the foundation:
with open("data.txt", "r") as f:
content = f.read()Breaking this down:
withis the context manager that automatically closes the file when you complete the indented code below the statement, even if an error arises. Always use this.openis a built-in function that handles the I/O for you. It has 2 arguments:The name of the file - in this case,
data.txtThe mode - in this case, we are reading from the file, denoted by
"r".
Below is a listing of the most common modes:
Mode | What it does |
|---|---|
| Reads (default) |
| Overwrites existing content |
| Appends to existing content |
| Read/Write binary |
Reading from a file
Once you’ve opened a file, you have two main ways to get the data into memory - and that’s either through read() or readlines():
# Using `read()`
with open("sales.csv", "r") as f:
content = f.read()
# content is one big string
print(type(content)) # <class 'str'>
# OR using `readlines()`
with open("sales.csv", "r") as f:
lines = f.readlines()
# lines is a list, each item is a row
print(type(lines)) # <class 'list'>
print(lines[0]) # 'name,department,sales,quarter\n'In my experience, I’ve found to use readlines() significantly more than read(), as it’s easier to work with.
A third option that is more memory-efficient is to iterate over the file object (in our example, f):
with open("sales.csv", "r") as f:
for line in f:
print(line.strip())Writing to a file
To write to a file, we’d flip the "r" to a "w":
with open("data.txt", "w") as f:
f.write("Alice,Engineering,95000,Q1\n")There’s a few things to note when writing to files:
"w"mode overwrites the file if it already exists (creates it if it doesn’t)."a"mode appends without destroying existing content.write()does not add a new line for you - you must include\nto the end of your string, as shown above.To write multiple lines at once,
writelines()takes a list:
rows = [
"Alice,Engineering,95000,Q1\n",
"Bob,Finance,82000,Q1\n",
"Carol,Marketing,67000,Q1\n",
]
with open("output.csv", "w") as f:
f.writelines(rows)File I/O with different file types and packages
Pandas and Polars
Plain Python (like above) is fine for raw text, but structured data formats have libraries that handle edge cases for you. For instance, when reading CSV file, you may want to use pandas or polars:
import pandas as pd
df = pd.read_csv("sales.csv")
import polars as pl
df = pl.read_csv("sales.csv")» For a rundown of what you can do once the data's loaded, I've covered 8 essential Pandas operations.
Writing with Pandas and polars is also straight forward:
# pandas
df.to_csv("output.csv", index = False)
# polars
df.write_csv("output.csv")JSON
The json module is built into the Python standard library. Use json.load() to read from a file:
import json
with open("config.json", "r") as f:
config = json.load(f)
db_host = config["database"]["host"]
debug_mode = config.get("debug", False)If you’re working with a string instead of a file (very common when consuming API responses), use json.loads() instead:
response_text = '{"status": "ok", "records": 42}'
data = json.loads(response_text)» Pandas can also read JSON directly when the data is tabular: df = pd.read_json()
To write using the json library, use json.dump():
import json
report = {
"department": "Engineering",
"total_sales": 95000,
"quarter": "Q1"
}
with open("report.json", "w") as f:
json.dump(report, f, indent=2)Excel files
One of the great things about Panda is that it takes multiple file types, including excel:
# Reading using Pandas
df = pd.read_excel("sales.xlsx", sheet_name="Q1 Data")
# Writing using Pandas
df.to_excel("output.xlsx", sheet_name="Q1 Data", index=False)YAML files
Yet Another Markup Language (YAML) is heavily used in projects in 2026 - to read/write them natively, you’ll need to install pyyaml:
pip install pyyamlimport yaml
with open("config.yaml", "r") as f:
config = yaml.safe_load(f)» Always use safe_load(), never load(). The load() function can execute arbitrary Python code embedded in a YAML file, which is a real security risk if you’re loading files from untrusted sources.
Writing is also straight-forward:
import yaml
with open("config.yaml", "w") as f:
yaml.dump(config, f, default_flow_style=False)What file formats do you work with most in your day-to-day? Are there any you'd want to see covered in more depth? Reply and let me know - I read every response.
Happy coding!
📧 Join the Python Snacks Newsletter! 🐍
Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:
Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.
Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.
Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.
You can unsubscribe at any time.
Interested in starting a newsletter or a blog?
Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.
If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.
This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.



