PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » File Handling » Python Write to File

Python Write to File

Updated on: December 4, 2026 | 4 Comments

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() and writelines(), plus print(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
    • Example: Write to a Text file in Python
    • Writing To An Existing File
  • 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 ModeDescription
wOpen 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.
wbOpen 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.
aOpens 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.
abOpen a binary file for appending. New data is added at the end of the file.
xExclusive creation. Create a new file and open it for writing. If the file already exists, Python raises a FileExistsError instead of overwriting it.
Python file write modes

Steps for Writing Data into a File in Python

To write into a file, Please follow these steps:

  1. 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.

  2. Open file in write mode

    Pass file path and access mode w to the open() function. The access mode opens a file in write mode.
    For example, fp= open(r'File_Path', 'w')

  3. Write content into the file

    Once a file is opened in the write mode, write text or content into the file using the write() method.
    For example, fp.write('new text').
    The write() 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.

  4. 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.

  5. Append content at the end of the file

    Pass file path and access mode a to the open() function to open a file in append mode.
    For example, fp= open(r'File_Path', 'a')
    Next, use the write() 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.

text = "This is new content"
# writing new content to the file
fp = open("write_demo.txt", 'w')
fp.write(text)
print('Done Writing')
fp.close()

# Open the file for reading the new contents
fp = open("write_demo.txt", 'r')
print(fp.read())
fp.close()Code language: Python (python)
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.

File after writing a text in it
File after writing a text in it

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:

fp = open(r"E:\demos\files\write_demo.txt", 'w')
fp.write('This is new content')
fp.close()
Code language: Python (python)

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.

file_path = r"E:\demos\files\write_demo.txt"
fp = open(file_path, 'r')
print(fp.read())
fp.close()

# overwriting existing content of a file
fp = open(file_path, 'w')
fp.write("This is overwritten content")
fp.close()

# Read file
fp = open(file_path, 'r')
print("Opening file again..")
print(fp.read())
fp.close()Code language: Python (python)

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.

MethodDescription
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.
file write methods

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:

person_data = ['Name: Emma', '\nAddress: 221 Baker Street', '\nCity: London']
# writing string and list of lines to a file
fp = open("write_demo.txt", "w")
fp.writelines(person_data)
fp.close()

# opening the file in read mode
fp = open("write_demo.txt", "r")
print(fp.read())
fp.close()Code language: Python (python)

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).

File after writing list into it
File after writing list into it

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.

name = "Written using a context manager"
with open("Write_demo.txt", "w") as f:
    f.write(name)

# opening the file in read mode to access the file
with open("Write_demo.txt", "r") as f:
    print(f.read())Code language: Python (python)

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.

name = '\nEmma'
address = ['\nAddress: 221 Baker Street', '\nCity: London', '\nCountry:United Kingdom']
# append to file
with open("Write_demo.txt", "a") as f:
    f.write(name)
    f.writelines(address)

# opening the file in read mode to access the file
with open("Write_demo.txt", "r") as f:
    print(f.read())
Code language: Python (python)

Output:

Written using a context manager
Emma
Address: 221 Baker Street
City: London
Country:United Kingdom
File after appending text
File after appending text

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.

name2 = "Antony\n"
address2 = ["224 Baker Street\n", "London\n"]

with open("Write_demo.txt", "a") as f:
  f.write(name2)
  f.writelines(address2)
  print(f.read())Code language: Python (python)

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.

name = '\nAntony'
address = ['\nAddress: 221 Baker Street', '\nCity: London', '\nCountry:United Kingdom']
# append to file
with open("Write_demo.txt", "a+") as f:
    f.write(name)
    f.writelines(address)
    # move file handle to the start
    f.seek(0)
    print(f.read())Code language: Python (python)

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:

# Write and Read
with open("Write_demo.txt", "w+") as f:
    f.write('Kelly')
    # move file handle to the start
    f.seek(0)
    print(f.read())Code language: Python (python)

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'.

text = "This is a sample string stored in binary format"

with open("Writedemo.bin", "wb") as file:
    # convert the string to bytes before writing
    file.write(text.encode("utf-8"))

# you can also write raw bytes directly
with open("data.bin", "wb") as file:
    file.write(bytes([65, 66, 67]))

with open("data.bin", "rb") as file:
    print(file.read())
# Output b'ABC'Code language: Python (python)

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.

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("Café, naïve, 😀\n")Code language: Python (python)

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.

score = 42

with open("results.txt", "w", encoding="utf-8") as f:
    count = f.write("Hello\n")
    print(count)  # 6 characters written

    # f.write(score) would raise TypeError: write() argument must be str, not int
    f.write(str(score) + "\n")

    # print() converts values and adds a newline
    print("Total:", 99, file=f)Code language: Python (python)

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.

from pathlib import Path

path = Path("pathlib_demo.txt")
path.write_text("Hello from pathlib\n", encoding="utf-8")
print(path.read_text(encoding="utf-8"))
# Output Hello from pathlibCode language: Python (python)

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.

try:
    with open("report.txt", "x", encoding="utf-8") as f:
        f.write("First version of the report")
except FileExistsError:
    print("report.txt already exists, so it was not overwritten")Code language: Python (python)

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().

import time

with open("progress.log", "w", encoding="utf-8") as f:
    for step in range(1, 4):
        f.write(f"Step {step} done\n")
        # push the buffered data to the file now
        f.flush()
        time.sleep(1)Code language: Python (python)

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). Use w to overwrite, a to append, x to create a new file only, and add + to also read, or b for binary data.
  • Use write() for a single string and writelines() for a list of strings. Neither adds newlines for you.
  • Prefer the with statement so the file is always closed, and pass encoding="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.

Filed Under: Python, Python File Handling

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python File Handling

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes
In: Python Python File Handling
TweetF  sharein  shareP  Pin

  Python File Handling

  • File Handling In Python
  • Create File in Python
  • Open a File in Python
  • Read File in Python
  • Write to File in Python
  • Python File Seek
  • Rename Files in Python
  • Delete Files in Python
  • Copy Files in Python
  • Move Files in Python
  • List Files in a Directory
  • File Handling Quiz

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com