How to Write to a Text File in Python

Python how to write to a file

In Python, you can write to a text file by the following procedure:

  1. Open a file.
  2. Write to the file.
  3. Close the file.

For example:

with open("example.txt", "w") as f:
    f.write("Hello world!")

This piece of code creates a new file called example.txt and writes "Hello World" into it.

In this guide, you are going to learn the basics of writing to a file in Python.

Python How to Write to a File in Detail

To write to a file in Python, use these three steps:

  1. Open a text file with the open() function.
  2. Write text to the opened file with the write() method.
  3. Finally, close the file using the close() method. Another options is to use the with statement that automatically closes the file for you. In this guide, I’m going to use the with statement.

The syntax for the open() function is as follows:

open(path_to_a_file, mode)

Where:

  1. path_to_a_file is the path to the file you want to open. If no file is found, a new one is created.
  2. mode specifies in which state you want to open the file. Use the mode 'w' to write to the file and 'a‘ to append to a file (add text to the end of the file).

The open() function returns a file object. This file object has two useful methods for writing text to the file:

  1. write() that writes a single string to the text file.
  2. writelines() that writes a list of strings to the file (or any other iterable, such as a tuple or set of strings).

Let’s see how to use these file writing methods.

The write() Method in Python

The write() method takes a string argument. It writes this argument into the opened file.

For example, let’s create a list of strings and use the write() method to write each of the strings into the file using a for loop:

words = ["This ", "is ", "a ", "test"]
with open("example.txt", "w") as f:
    for word in words:
        f.write(word)

As a result, a file called example.txt is created with the following content:

This is a test

Notice how each string is written to the same line by default.

If you want to have each word appear on a separate line, write the line break character '\n' after writing a string to the file.

For example:

words = ["This", "is", "a", "test"]
with open("example.txt", "w") as f:
    for word in words:
        f.write(word)
        f.write("\n")

In the example.txt file the result looks like this:

This
is
a
test

This is one way to write into a file.

But in the case of multiple strings, you can use the writelines() method to write them all into a file on the same go.

The writelines() Method in Python

The writelines() function takes an iterable object, such as a list, that contains strings to be written into the opened file.

For example, let’s repeat the above example using the writelines() method:

words = ["This ", "is ", "a ", "test"]

with open("example.txt", "w") as f:
    f.writelines(words)

After running this piece of code, the example.txt file looks like this:

This is a test

Now you know how to write text to a file in Python. Next, let’s take a look at how to add text at the end of an already existing text file.

How to Append to a File in Python

To add text at the end of a file after the existing lines of text, use the write mode 'a'. This mode is called the appending mode. And appending means adding to the end of something.

For example:

# Let's first write to a file
with open("example2.txt", "w") as f:
    f.write("This is ")
 
# Then let's reopen the file and append some text to it:
with open("example2.txt", "a") as f:
    f.write("just another test.")

Here the result is a file called example2.txt with the following contents:

This is just another test.

As you can see, the last bits of text were successfully added to the end of the text file.

Conclusion

Today you learned how to write to a file in Python.

To recap, to write to a file, follow these three steps:

  1. Open the file with the open() function.
  2. Write to the file using either write() or writelines() method.
  3. Always close the file after writing. You can do this with the close() method or by using the with statement that automatically closes the file after writing.

Thanks for reading.

Happy coding!

See Also

10 Python Snippets to Code Like a Pro

Common For Loop Examples in Python

Share on facebook
Share on twitter
Share on linkedin

Leave a Comment

Your email address will not be published.