Programs often need to save data, such as results, logs, or reports, to files so it can be used later. Python has built-in functions for writing data to files, and you don’t need to import any module to use them.
You can open a file and write new content to it, overwrite its existing content, or append new content to the end of it.
After reading this tutorial, you’ll learn: –
- Writing into both text and binary files
- The different modes for writing a file
- Writing single or multiple lines in a file.
- The methods for writing a file,
write()andwritelines(), plusprint(file=...). - Appending new content at the end of an existing file
- Opening a file for both reading and writing
- Writing with a specific encoding, writing numbers, and using
pathlib
Table of contents
- Access Modes for Writing a file
- Steps for Writing Data into a File in Python
- File Write Methods
- writelines(): Write a list of lines to a file
- with Statement to Write a File
- Appending New Content to an Existing File
- Append and Read on the Same File
- Writing to a Binary File
- Specify the encoding when writing
- Write numbers and use print() to write to a file
- Write a file using pathlib
- Avoid overwriting an existing file
- Flush Data to the File Immediately
- Summary
Access Modes for Writing a file
The access mode specifies the purpose of opening a file.
Whenever you want to write text to a file, you must open it in one of the access modes below. A file can be opened to read, write, or append, and some modes allow several operations at once.
To write the contents into a file, we have to open the file in write mode. Open a file using the built-in function called open(). It takes two main parameters, the file name (or path) and the access mode, and returns a file object.
To write to a file or overwrite its contents, use one of the modes described in the following table.
| Access Mode | Description |
|---|---|
w | Open a file for writing. In the case of an existing file, it truncates the existing content and places the filehandle at the beginning of the file. A new file is created if the mentioned file doesn’t exist. |
w+ | Open a file for both reading and writing. In the case of the existing file, it will truncate the entire content and place the filehandle at the beginning of the file. |
wb | Open a binary file for writing. The FileHandle is placed at the beginning of the file, and existing content will be truncated. A new file is created otherwise. |
a | Opens a file for writing. The FileHandle will be placed at the end of the file. In the case of the existing file, the new content will be added after the existing content. A new file will be created otherwise. |
a+ | Open a file for appending as well as reading. The FileHandle is placed at the end of the file. In the case of the existing file, the new content will get added after the existing content. A new file is created otherwise. |
ab | Open a binary file for appending. New data is added at the end of the file. |
x | Exclusive creation. Create a new file and open it for writing. If the file already exists, Python raises a FileExistsError instead of overwriting it. |
Steps for Writing Data into a File in Python
To write into a file, Please follow these steps:
- Find the path of a file
We can read a file using both relative path and absolute path. The path is the location of the file on the disk.
An absolute path contains the complete directory list required to locate the file.
A relative path contains the current directory and then the file name. - Open file in write mode
Pass file path and access mode
wto theopen()function. The access mode opens a file in write mode.
For example,fp= open(r'File_Path', 'w') - Write content into the file
Once a file is opened in the
writemode, write text or content into the file using the write() method.
For example,fp.write('new text').
Thewrite()method will add new text at the beginning of a file. For an existing file, this new content will replace the existing content. If the file is not already present a new file will be created, and content is written into it. - Close file after completing the write operation
We need to make sure that the file will be closed properly after completing the file operation. Use
fp.close()to close a file. - Append content at the end of the file
Pass file path and access mode
ato theopen()function to open a file in append mode.
For example,fp= open(r'File_Path', 'a')
Next, use thewrite()method to write content at the end of the file without deleting the existing content
Example: Write to a Text file in Python
The following code shows how to write a string into a new file. In this example, we are writing a single line into a file.
Done Writing This is new content
In the above example, write_demo.txt didn’t exist, so a new file was created with that name. We used a relative path, and the content was written at the beginning of the file.

Note: With a relative path, the file is created in the current working directory (usually the folder you run the script from). Use an absolute path if you want to create the file in a different directory.
An absolute path contains the entire path to the file or directory that we need to access. It includes the complete directory list required to locate the file.
For example, E:\PYnative\files_demos\write_demo.txt is an absolute path to write_demo.txt on Windows. The r prefix makes it a raw string, so the backslashes are not treated as escape characters.
Example:
Writing To An Existing File
When you open an existing file in write mode (w), its existing content is erased, and the file handle is placed at the beginning of the file.
In the below example, we are reading a file to view the old contents. Next, we are opening a file in the write mode to write the new content. We can see that the existing content has been overwritten with the new content.
Output
This is new content Opening file again.. This is overwritten content
File Write Methods
File objects provide two methods for writing. You don’t need to import any module to use them.
| Method | Description |
|---|---|
write() | Writes a string to the file and returns the number of characters written. It accepts only a string (in text mode). Anything else raises TypeError: write() argument must be str, so convert numbers with str() first. |
writelines() | Writes every string from an iterable, such as a list, to the file. It does not add newline characters, so include \n yourself. |
writelines(): Write a list of lines to a file
You can write multiple lines at once using the writelines() method. Pass it a list of the strings you want to add to the file. Use this method when you want to write a list into a file.
lines = [str1, str2, str3]
file_obj.writelines(lines)Code language: Python (python)
Each string in the list is written to the file represented by file_obj, one after another.
Example:
Output
Name: Emma Address: 221 Baker Street City: London
The list of strings was written to the file. Because writelines() doesn’t add line breaks, we added ‘\n’ at the start of each string so that each one appears on a new line. A common alternative is f.writelines(line + '\n' for line in lines).

with Statement to Write a File
The recommended way to open a file is with the with statement together with the open() function. The general syntax is as follows.
with open(file_path, access_mode) as f:
# write to f hereCode language: Python (python)
The main advantages of opening a file with the with statement are:
- The file is closed automatically when the block ends, even if an error occurs inside it.
- All buffered data is written to the disk when the file is closed, so you don’t lose any output.
- The resources tied up with the file are released, and your code is shorter and easier to read.
Let us see with an example how we can use this to open a file for writing.
Output
Written using a context manager
Appending New Content to an Existing File
With the access mode set to a, open() places the file handle at the end of the file, so the write() and writelines() methods add new text after the existing content instead of replacing it.
Now let’s add some content to the existing ‘Write_demo.txt’ file.
Output:
Written using a context manager Emma Address: 221 Baker Street City: London Country:United Kingdom

Append and Read on the Same File
In the above example, the new content was added after the existing content. Then we opened the file again to read it.
As you can see, we opened the file twice: once for appending and once for reading.
A file opened in a mode is write-only. If you try to read from it without opening it again, you get an UnsupportedOperation exception.
Output
UnsupportedOperation: not readable
To append and read with the same file object, use the access mode a+. Adding + to a mode opens the file for both reading and writing.
Example: Append and Read
In append mode, the file handle is at the end of the file after writing. If you call read() right away, you get an empty string. Use the seek() method on the file object to move the file handle back to the beginning first.
Output
Written using a context manager Emma Address: 221 Baker Street City: London Country:United Kingdom Antony Address: 221 Baker Street City: London Country:United Kingdom
If you want to both write and read, use the access mode w+. It opens a file for both writing and reading, and places the file pointer at the beginning of the file. The content of an existing file is erased. To read and write without erasing the content, use r+ instead (the file must already exist).
Example:
Output:
Kelly
Writing to a Binary File
By default, the open() function opens a file in text mode, where you read and write strings (r and w). Files such as images, audio, or any non-text data must be opened in binary mode, where you read and write bytes instead of strings.
To read or write a binary file, add b to the access mode: wb for writing and rb for reading.
As with w, the wb mode creates the file if it doesn’t exist and erases the content of an existing file. Note that write() in binary mode accepts only bytes, so a string must be encoded first with encode(). Passing a plain string raises TypeError: a bytes-like object is required, not 'str'.
The first block creates a binary file and writes the encoded string to it. The second writes three raw bytes, which are the character codes for A, B, and C.
Specify the encoding when writing
When you write text, Python converts it to bytes using an encoding. If you don’t specify one, Python uses your operating system’s default, which can differ between computers. Characters such as accented letters or emoji may then be saved incorrectly or cause a UnicodeEncodeError. Pass encoding="utf-8" to make your files portable.
Write numbers and use print() to write to a file
The write() method accepts only strings, so convert other values with str() or an f-string first. It also returns the number of characters written. Alternatively, the print() function can write to a file through its file argument. It converts values to strings and adds a newline automatically.
The file results.txt now contains:
Hello 42 Total: 99
Write a file using pathlib
The pathlib module offers a shortcut for simple writes. Path.write_text() opens the file, writes the string, and closes the file in a single call. It always overwrites the existing content.
Avoid overwriting an existing file
Opening a file in w mode silently erases its content. If you want to create a file only when it doesn’t exist yet, use x mode, which raises an error instead of overwriting.
Tip: To write structured data, use the dedicated modules: csv for spreadsheets and json for JSON files.
Flush Data to the File Immediately
Python doesn’t write each write() call to the disk right away. It collects the data in a buffer and writes it in larger chunks, which is faster. The data is saved when the buffer fills up or when the file is closed. If another program needs to see the data immediately, for example, a log file that someone is watching, call flush().
You can also pass flush=True to print(), for example, print("Step done", file=f, flush=True).
Summary
In this article, you learned how to write to files in Python:
- Open a file with
open(path, mode). Usewto overwrite,ato append,xto create a new file only, and add+to also read, orbfor binary data. - Use
write()for a single string andwritelines()for a list of strings. Neither adds newlines for you. - Prefer the
withstatement so the file is always closed, and passencoding="utf-8"for text files. - Convert numbers and other values to strings before writing, or use
print(..., file=f). - In binary mode, write
bytes, for example,text.encode("utf-8"). - For quick one-off writes,
pathlib.Path.write_text()is a convenient shortcut.
