The basic way to write to a file in Python
Writing to a file in Python means using the open() function to create or open a file, then using the write() method to add text to it. Python handles the details of connecting to your file system, so you only need to tell it the filename and what text you want to store.
The simplest approach uses three lines: open the file, write your text, and close the file. Here is the actual code you type:
file = open("myfile.txt", "w") file.write("Hello, this is my text") file.close()
The "w" mode means "write" — it creates a new file or replaces an existing one with that name. If you want to add text to the end of an existing file instead of replacing it, use "a" for append mode.
Key Takeaways
- Use open(filename, "w") to create a new file or overwrite an existing one, and open(filename, "a") to add text to the end of a file that already exists.
- The write() method adds a single string to the file, and writelines() adds multiple lines from a list in one command.
- Always close the file with file.close() or use a with statement, which closes automatically and prevents data loss.
- Python creates the file in the same folder as your script unless you specify a different path, such as "C:/Users/YourName/Documents/myfile.txt".
- Newline characters like \n do not appear as visible line breaks in your code — you must add them to your string if you want separate lines in the file.
Using the with statement to close files automatically
Closing a file manually works, but forgetting to close it can cause data loss or lock the file so other programs cannot use it. The with statement closes the file automatically when you are done, even if your code hits an error.
Here is the same example using with:
with open("myfile.txt", "w") as file: file.write("Hello, this is my text")
Notice the indentation — everything inside the with block (the indented lines) happens while the file is open. Once the block ends, Python closes the file automatically. This is the safer way to write files, and most Python code uses it.
Writing multiple lines at once
If you have several lines to write, you can use writelines() to add them all in one command. This method takes a list of strings and writes each one to the file in order.
lines = ["First line\n", "Second line\n", "Third line\n"] with open("myfile.txt", "w") as file: file.writelines(lines)
Notice the \n at the end of each string — that is the newline character, which tells Python to start a new line in the file. Without it, all three lines would appear on one line in the file. The \n does not show up when you read the file; it just controls where line breaks happen.
You can also write multiple lines by calling write() several times, once for each line. Both approaches work; writelines() is faster when you have many lines.
Appending text to an existing file
When you open a file with "w" mode, Python erases everything in it and starts fresh. If you want to keep the old text and add new text to the end, use "a" for append mode instead.
with open("myfile.txt", "a") as file: file.write("This text goes at the end\n")
Append mode creates the file if it does not exist, just like write mode does. The difference is that if the file already has text in it, append mode leaves that text alone and adds your new text after it. Write mode would delete the old text first.
Handling file paths and locations
By default, Python creates or opens files in the same folder where your script is running. If you want to write to a different folder, you need to specify the full path to that folder.
On Windows, use forward slashes or double backslashes in the path:
with open("C:/Users/YourName/Documents/myfile.txt", "w") as file: file.write("Hello")
On Mac or Linux, paths start with a forward slash:
with open("/Users/YourName/Documents/myfile.txt", "w") as file: file.write("Hello")
If the folder does not exist, Python will raise an error. You must create the folder first using your file manager or another tool. Python can only write to folders that already exist.
Writing numbers and other data types to files
The write() method only accepts strings — text. If you want to write a number, a list, or another data type, you must convert it to a string first using str().
number = 42 with open("myfile.txt", "w") as file: file.write(str(number))
If you forget to use str(), Python will show an error message like "write() argument must be str, not int". This is a common mistake when you are starting out.
For more complex data like dictionaries or lists, you have two main options. You can convert them to strings manually and write them, or you can use the json module to write them in a standard format that other programs can read. JSON format is more reliable if you plan to read the file back into Python later.
Common mistakes when writing to files
The most common error is forgetting the newline character. If you write three lines without \n at the end of each one, they will all appear on a single line in the file. Always add \n unless you specifically want text on the same line.
Another frequent mistake is using "w" mode when you meant to use "a" mode. Write mode erases the file, so if you run your script twice, the first run's data disappears. If you want to keep adding to the same file over time, use append mode.
Forgetting to close the file (or not using with) can cause the file to stay locked or data to not save properly. Always use with to ensure the file closes automatically. If you must use open() and close() separately, put the close() call in a try/finally block so it runs even if an error occurs.
Frequently Asked Questions
What is the difference between write and append mode?
Write mode ("w") erases the file and starts fresh, so any old text is lost. Append mode ("a") keeps the old text and adds your new text to the end. Use write mode when you want a brand new file, and append mode when you want to add to an existing file.
Do I have to use the with statement?
No, but you should. The with statement closes the file automatically, which prevents data loss and file-locking problems. If you use open() without with, you must remember to call close() yourself, and it is easy to forget.
How do I write to a file in a different folder?
Specify the full path in the filename. On Windows, use "C:/Users/YourName/Documents/myfile.txt" or "C:\\Users\\YourName\\Documents\\myfile.txt". On Mac or Linux, use "/Users/YourName/Documents/myfile.txt". The folder must already exist.
What happens if the file already exists?
In write mode ("w"), Python erases the old file and creates a new one. In append mode ("a"), Python keeps the old file and adds your text to the end. Choose the mode based on whether you want to keep or replace the old content.
Can I write numbers directly to a file?
No, write() only accepts strings. Convert numbers to strings first using str(number). For complex data like lists or dictionaries, consider using the json module, which formats the data in a way that is easy to read back into Python later.