Python gives you three main ways to write to a file, and which one you use depends on what you're writing and whether the file already exists
The simplest method is the open() function with write mode. You tell Python to open a file, give it a name, and specify that you want to write to it. Python creates the file if it doesn't exist, or replaces it entirely if it does. This is the fastest way to get your free guide, but it means you lose whatever was in the file before.
The second method is append mode, which adds your new data to the end of an existing file instead of erasing it. The third is context managers — a way of writing that automatically closes the file when you're done, which prevents data loss if something goes wrong mid-write.
All three use the same basic structure: open the file, write your data, close the file. The differences are in the details of what mode you choose and how you handle the closing step.
Key Takeaways
- The open() function with 'w' mode creates a new file or replaces an existing one; use 'a' mode to add to the end instead.
- The write() method takes a string and puts it in the file; writelines() writes a list of strings without adding line breaks between them.
- Using a with statement closes the file automatically, even if your code hits an error, which prevents data corruption.
- Python does not add newline characters on its own — if you want each piece of data on a separate line, you must include \n in your string.
Write mode versus append mode: what happens to existing data
When you open a file with 'w' (write mode), Python erases everything that was in the file before. This happens the moment you open it, not when you actually write something. If you open a file that contains 500 lines and then change your mind, those 500 lines are already gone.
Append mode, written as 'a', adds your new data to the end of the file without touching what's already there. Use this when you're logging events, collecting data over time, or adding records to a file that other parts of your program depend on.
A third mode, 'x', creates a new file but fails if the file already exists. This is useful when you want to be certain you're not overwriting something important, but most beginners use 'w' or 'a' instead.
The basic structure: open, write, close
Here is the simplest way to write to a file:
file = open('myfile.txt', 'w') file.write('Hello, world') file.close()
The first line opens a file called myfile.txt in write mode. Python creates the file in the same folder as your script. The second line writes the string 'Hello, world' to the file. The third line closes the file, which tells Python to finish writing and release the file so other programs can use it.
If you forget to close the file, Python will eventually close it when your program ends, but data may not be written to disk until then. On some systems, if your program crashes before closing, you lose what you wrote. Closing is not optional — it is a step you must do.
Why the with statement prevents data loss
The with statement is a safer way to write files because it closes the file automatically, even if your code hits an error:
with open('myfile.txt', 'w') as file: file.write('Hello, world')
Everything indented under the with line is inside the block. When Python finishes that block — whether because the code ran successfully or because an error stopped it — the file closes automatically. You do not have to remember to call close().
This matters because if you write data, then your code tries to divide by zero or access a variable that doesn't exist, the error stops your program. With the with statement, the file still closes and your data is saved. Without it, the file may stay open and your data may never reach the disk.
Writing multiple lines and lists of data
The write() method takes one string at a time. If you want each piece of data on a separate line, you must include the newline character \n in your string:
with open('myfile.txt', 'w') as file: file.write('Line one\n') file.write('Line two\n') file.write('Line three\n')
Without the \n, all three lines would run together as one long string in the file.
If you have a list of strings, the writelines() method writes them all at once. It does not add newlines between them, so you must include \n in each string:
lines = ['First\n', 'Second\n', 'Third\n'] with open('myfile.txt', 'w') as file: file.writelines(lines)
This writes all three lines to the file in one call instead of three separate calls to write(). The result is identical — it is just a shorthand when you already have your data in a list.
Converting numbers and other data types to strings
The write() method only accepts strings. If you try to write a number, Python stops with an error. You must convert the number to a string first using the str() function:
count = 42 with open('myfile.txt', 'w') as file: file.write(str(count))
The str() function turns the number 42 into the string '42', which write() can handle. Without it, you get a TypeError.
For more complex data like lists or dictionaries, you have two options. You can convert them to a string using str(), which gives you the Python representation. Or you can use the json module to convert them to JSON format, which is easier to read back in later. JSON is a standard format that many programming languages understand, so it is useful if another program needs to read your file.
Appending data without erasing what's already there
Use append mode 'a' when you want to add to a file instead of replacing it. This is common for log files, where you write a new entry each time something happens:
with open('log.txt', 'a') as file: file.write('Event occurred at 3:45 PM\n')
If log.txt already contains 100 lines, this adds a new line at the end without touching the first 100. If the file doesn't exist, Python creates it, just like in write mode.
Append mode is also safer when multiple parts of your program write to the same file. If one part opens the file in write mode while another is still using it, you can lose data. Append mode is less likely to cause this problem, though it is not a complete solution — for serious applications, you need a database instead.
Common mistakes and how to avoid them
The most common mistake is forgetting the newline character. You write three pieces of data and expect three lines, but they all run together because you didn't include \n. Always add \n at the end of each line unless you have a specific reason not to.
The second mistake is opening a file in write mode when you meant append. You lose data you needed. If you are not sure whether the file exists or what's in it, use append mode instead — it is safer.
The third mistake is trying to write a number or list directly without converting it to a string first. Python will stop with an error. Use str() to convert anything that is not already a string.
The fourth mistake is not closing the file. Use the with statement and you will never have this problem. If you use the older open() and close() method, write the close() line when ready after you write the data, before you add any other code. That way you will not forget it.
Frequently Asked Questions
What happens if I write to a file that doesn't exist?
Python creates the file for you. It appears in the same folder as your script. If the folder doesn't exist, Python stops with an error — you must create the folder first.
Can I write to a file while another program has it open?
It depends on the program and the operating system. On most systems, you can write to a file that another program is reading, but not one that another program is writing to. If you get an error saying the file is in use, close it in the other program first.
How do I add data to the middle of a file, not just the end?
You cannot do this directly. You must read the entire file into memory, insert your data at the right place, then write the whole thing back. For large files, this is slow. If you need to edit files often, use a database instead of text files.
What is the difference between write and writelines?
write() takes one string. writelines() takes a list of strings and writes them all. Neither adds newlines automatically — you must include \n in your strings if you want separate lines.
Do I need to use the with statement, or can I just use open and close?
The with statement is safer because it closes the file automatically, even if your code hits an error. Using open() and close() works, but you must remember to close it, and if an error happens first, the file may not close. For new code, always use with.