From the course: Python: Working with Files

Write data to a file in Python - Python Tutorial

From the course: Python: Working with Files

Write data to a file in Python

- [Instructor] When developing a Python program, sometimes you'll want to output data to a file. We've already looked at how to read data from a file, but in this chapter, we'll explore writing data. The first step is to open the file in the correct mode, either w for write mode or a for append mode. Let's look at write mode first. To write data to a file, we can use the write method on the file object, writer.write, and we'll write hello. This will create the num series text file and give it the content hello. To make this a little more interesting, let's say we want to write the numbers 0 through 49 to this file. To do this, we can create a loop, for x in range 50. For each number, we'll create a string that we'll write out to the file. We'll give it the number and a new line character, then we'll write the content, writer.write(content). This will write out the numbers 0 through 49, where each number is on its own line. Let's call the function. We'll run it in our terminal. In our desktop, we can see the num series text file. If we open it up, here are the numbers 0 through 49. In this example, we generated a piece of content and then wrote it out to our file. Another option is to generate a larger string with all of your content and then write out to the file once. It's up to you whether you want to slowly build up your file or generate the content all at once and then perform one file interaction. However, it's important to note that when we reopen a file and write to it, it erases any content that previously existed in the file. In our example, we wrote to the same file multiple times, but we were using the same file object. If we reopened the file in write mode and tried to write to it again, it would erase our number series. Let's try overwriting our content. We'll overwrite it with the numbers 50 to 99. Let's call it the function and execute our program. Let's see if the file changed. We'll open it up and now we have the numbers 50 to 99. We overwrote the previous content. Now, if we wanted to append these numbers instead of overwriting the previous content, we could use append mode. All we have to do is change w to a. This will open our file in the correct mode to append the items. Although we don't have to, we'll also change the name of our function so it makes a little more sense. Now we're appending content. Let's execute our program. If we open up the file again, our file has the numbers 0 to 99. With Python, we get many useful methods for writing data to files.

Contents