Textlogo_codingem_white

Programming tips for everyone

Learn Python—How to Write to a File

Python how to write to a file

In this guide you learn basics of Python: How to write to a file.

In short, you can write text to a new text file called example.txt with the following:

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


Python How to Write to a File in Detail

Let’s take a deeper look at how to write to files in Python.

The procedure is simple:

  • Open a (new) text file with the open() function.
  • Write text to the opened file with the write() method.
  • 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 basic syntax for open() function is this:

open(path_to_a_file, mode)


Where:

  • path_to_a_file is the path to the file you want to open. If no file is found, a new one is created.
  • 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 possible text in the file).


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

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


Examples of Writing to a File

Let’s see examples of how to write and append to a file in Python using both write() and the writelines() methods and both writing modes 'a' and 'w'.


How to Write to a File in Python

Let’s write a list of strings into a text file using the writing mode 'w'. As you learned, you can use the write() method or the writelines() method.

Let’s take a look at using write() first:

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


Next, let’s use the writelines() to do the same:

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

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


Now if you’d like each word appear on a separate line, just 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


How to Append to a File in Python

Now you know how to write text to a file in Python. But what if you want to add text to the end of an existing file with some text in it? In this case, you can use the write mode 'a' described earlier to append text to the end of the file.

For example:

# Let's first write to a file
with open("example2.txt", "w") as f:
    f.write("This is ")
 
# Then let's open the file and append 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.


Conclusion

Writing to a file in Python is a simple procedure:

  • Open the file with the open() function
  • Write to the file using either write() or writelines() method
  • Always close the file after writing. You can do this with the close() method. Better yet, you can use the with statement that automatically closes the file for you after writing.


You May Find Insightful

Share on facebook
Share on twitter
Share on linkedin

Related Articles

Artturi Jalli

Technical Writer

Entrepreneur, Software Engineer, Mobile App Dev, MSc Physics Student, And Tech Enthusiast from Finland

artturi@codingem.com

My Personal Favorites
Sponsor

Buy an Online Course

Lorem ipsum dolor sit amet consectetur adipiscing elit dolor
Explore Categories

Web Development