Hey Pythonistas,
I’m just getting started with file handling in Python, and I need to save some data to a text file. I’ve seen people mention things like open()
and .write()
, but I’m not sure how they work together.
How do you properly write to a file in Python? Also:
- How do you append vs. overwrite?
- How do you make sure the file closes properly?
- Can I write lists or variables too?
Would love a beginner-friendly example (or two)!
Great question! Learning how to write to a file in Python is a fundamental step in working with data, whether you’re logging, exporting results, saving scraped data, or even generating HTML or CSV files.
Let’s walk through the essentials.
Here’s the simplest way to write text to a file in Python:
file = open("output.txt", "w")
file.write("Hello, world!")
file.close()
Code language: JavaScript (javascript)
This creates a file called output.txt
and writes “Hello, world!” into it. The "w"
means “write mode,” which overwrites the file if it already exists. Make sure your script closes the file afterwards with file.close()
, otherwise it will stay in memory for as long as your script runs.
Using a with
block is the recommended way to write to files in Python. It automatically closes the file for you, even if something goes wrong.
with open("output.txt", "w") as file:
file.write("Hello again!\n")
file.write("This is a second line.\n")
Code language: JavaScript (javascript)
Clean, safe, and readable.
Mode | Description |
"w" | Write mode, overwrites existing file |
"a" | Append mode, adds to the end of file |
with open("output.txt", "a") as file:
file.write("Appending this line.\n")
Code language: JavaScript (javascript)
Use "a"
when you want to log events, like saving image processing results over time.
Let’s say you have some data:
name = "Alice"
score = 95
Code language: JavaScript (javascript)
To write this to a file:
with open("scores.txt", "w") as file:
file.write(f"{name} scored {score} points.\n")
Code language: JavaScript (javascript)
Python f-strings (f"..."
) make this super easy and clean.
You can use .writelines()
to write multiple lines at once:
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("list.txt", "w") as file:
file.writelines(lines)
Code language: JavaScript (javascript)
Make sure each string ends with \n or you’ll get one big run-on line.
If you want to write to a folder, make sure the folder exists:
with open("logs/output.txt", "w") as file:
file.write("Logging something...")
Code language: JavaScript (javascript)
Use os.makedirs()
if you want to create the folder first:
import os
os.makedirs("logs", exist_ok=True)
with open("logs/output.txt", "w") as file:
file.write("Ready to log.")
Code language: JavaScript (javascript)
If you’re working with images (maybe via Cloudinary or PIL), you might want to save metadata like this:
image_name = "sunset.jpg"
width = 1920
height = 1080
with open("image_info.txt", "w") as file:
file.write(f"Filename: {image_name}\n")
file.write(f"Dimensions: {width}x{height}\n")
Code language: JavaScript (javascript)
Great for organizing media files, debugging automation scripts, or documenting datasets.
- Forgetting to close the file. Use
with open(...)
to avoid this entirely. - Writing numbers directly. Use
str()
or f-strings..write()
only works with strings! - Not adding
\n
at the end of lines. Remember:.write()
doesn’t automatically add newlines. - Trying to write a list directly.
.write()
needs a string, not a list.
with open("user_log.txt", "a") as log:
while True:
entry = input("Type something (or 'q' to quit): ")
if entry == "q":
break
log.write(entry + "\n")
Code language: JavaScript (javascript)
Now, anything the user types gets appended to user_log.txt
.
If you’re working with dictionaries or structured data, consider using json.dump()
:
import json
data = {"user": "Alice", "score": 95}
with open("data.json", "w") as file:
json.dump(data, file)
Code language: JavaScript (javascript)
This is often used for configs, APIs, and image processing pipelines.
Task | Code Example |
Overwrite file | open("file.txt", "w") |
Append to file | open("file.txt", "a") |
Write a line | file.write("Text\n") |
Write many lines | file.writelines(["One\n", "Two\n"]) |
Best practice | Use with open(...) as file: |
Write variables | file.write(f"{var}\n") |
Write structured data | Use json.dump(data, file) |
Knowing how to write to a file in Python unlocks tons of possibilities, data logging, report generation, content creation, and much more. Whether you’re building a command-line tool or exporting image metadata from a cloud service, this is a fundamental skill you’ll use often.
Happy coding!