Home » Programming » Python » Python Write File

How to Write to a Text File in Python

This article will show you how to write to a file in the Python programming Language – examples included!

All files are, essentially, text files. Data is formatted and stored in various ways – comma-separated values for spreadsheets (CSV), plain text for text files (TXT), all the way to complex image formats for storing documents and images like PDF and JPG files.

Once the program you are building is up and running, you’ll want to be able to save the output it produces – so here’s how to get your own Python project writing data to a file.

Write Data to a File

To write to a file, simply use the built-in Python open() function.

The open() function opens the file at a given path and returns a file object which can then be used to interact with the file on disk.

# Create a file object to the file testFile.txt in the current directory
# The "w" parameter tells python that we wish to open the file for writing
myFile = open("testFile.txt", "w")

# Write some text to the file
myFile.write("Say hello to my little friend")

# Close the file - releasing it for use by other processes
myFile.close()

# Open the newly created file
# The "r" parameter tells python we only want to open the file for reading
myFile = open("testFile.txt", "r")

# Print the contents of the file to confirm that they were written
print(f.read())

Watch Out! Writing to an Existing File Will Overwrite!

If the file already exists using the above method, the file and its contents will be overwritten with a new file.

You can check if the file exists before trying to write to it first by following our tutorial here.

Append Data to an Existing File

Appending text to a file will leave the file’s contents (if it already exists) and add new data to the end of the file. If the file does not already exist, it will be created instead.

# Create a file object to the file testFile.txt in the current directory
# The "a" parameter tells python that we wish to open the file for appending
myFile = open("testFile.txt", "a")

# Append some text to a file
myFile.write("Say hello to my little friend")

# Close the file - releasing it for use by other processes
myFile.close()

# Open the newly appended file
# The "r" parameter tells python we only want to open the file for reading
myFile = open("testFile.txt", "r")

# Print the contents of the file to confirm that they were written
print(f.read())

Dealing with Permissions

Different environments and filesystems will behave differently.

The best way to deal with potential errors (e.g., not having write permission for a file) is just to try to do what you want to do and catch any resulting errors.

It’s easier to ask for forgiveness than permission.

try:
    with open('testFile.txt', "w") as myFile:
        # The file has been opened successfully
        # Using the with statement means there's no need to close the file - it will be closed automatically!
        # File read/write tasks can be done here
        # If an error encountered when dealing with the file, it will be handled below
except IOError:
    # If a file error is encountered, you can decide here what to do - retry, alert the user, try a different file name, etc
    # The IOError will specifically catch file read/write errors - other errors can be caught too if your circumstance requires 
    print('File Error!')

 

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment