How to Write to a Text File using Python
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!
- Getting Started with Solid
- Managing PHP Dependencies with Composer
- Getting Started with Express
- Getting Started with Electron
- How to deploy a .NET app using Docker
- Getting Started with Deno
- How to deploy an Express app using Docker
- Getting Started with Sass
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Moment.js
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js