Table of Contents
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:
PYTHONtext = "Hello, World!"
Now, let's use the open() function to open a file in write mode, as specified by the "w" argument:
PYTHONfile = 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.
PYTHONfile.write(text)
Finally, we close the file in order to save the changes:
PYTHONfile.close()
The entire code looks like this:
PYTHONtext = "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:
PYTHONtext = ["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:
PYTHONHello, World!This is a text file.
If you want to add a newline character to each string, you can use the join() function:
PYTHONtext = ["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!
How to Install Node on Windows, macOS and Linux
Managing PHP Dependencies with Composer
Getting Started with Express
How to deploy a .NET app using Docker
How to deploy a PHP app using Docker
How to deploy a Deno app using Docker
Using Puppeteer and Jest for End-to-End Testing
Build a Real-Time Chat App with Node, Express, and Socket.io
Getting User Location using JavaScript's Geolocation API
Using Push.js to Display Web Browser Notifications
Building a Real-Time Note-Taking App with Vue and Firebase
Setting Up Stylus CSS Preprocessor
