How to Write to a Text File using Python

Updated onbyAlan Morel
How to Write to a Text File using Python

Because Python is run on the back-end/server, it has access to the file system.

This means that Python can read and write files on the server, just like any other program.

In this post, we'll learn how to write to a text file in Python.

How to Write to a Text File in Python using write()

To write to a text file, first let's define what we want written to it:

PYTHON
text = "Hello, World!"

Now, let's use the open() function to open a file in write mode, as specified by the "w" argument:

PYTHON
file = open("hello.txt", "w")

When you use open you get back a file object. This file object has a write() method that you can use to write to the file.

PYTHON
file.write(text)

Finally, we close the file in order to save the changes:

PYTHON
file.close()

The entire code looks like this:

PYTHON
text = "Hello, World!" file = open("hello.txt", "w") file.write(text) file.close()

How to Write to a Text File in Python using writeLines()

Another way to write to a text file is to use the writeLines() function.

This function takes a list of strings as an argument and writes each string to a new line in the file.

Let's look at an example:

PYTHON
text = ["Hello, World!", "This is a text file."] file = open("hello.txt", "w") file.writelines(text) file.close()

Keep in mind that the writeLines() function does not add a newline character to the end of each string, so the output will look like this:

PYTHON
Hello, World!This is a text file.

If you want to add a newline character to each string, you can use the join() function:

PYTHON
text = ["Hello, World!", "This is a text file."] file = open("hello.txt", "w") file.writelines("\n".join(text)) file.close()

Conclusion

In this post, we learned how to write to a text file in Python.

Simply use the open() function to open a file in write mode, and then use the write() or writeLines() function to write to the file.

That's it for this post. Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.