Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Writing to a File

Now that you know how to read files, let’s dive into writing files. As with reading files, file objects have multiple methods that are useful for writing to a file.

write() writes a string to the file, and writelines() writes a sequence to the file. No line endings are appended to each sequence item. It’s up to you to add the appropriate line ending(s).

Here’s a quick example of using .write() and .writelines():

Python
with open('dog_breeds.txt', 'r') as reader:
    # Note: readlines doesn't trim the line endings
    dog_breeds = reader.readlines()

with open('dog_breeds_reversed.txt', 'w') as writer:
    # Alternatively you could use
    # writer.writelines(reversed(dog_breeds))

    # Write the dog breeds to the file in reversed order
    for breed in reversed(dog_breeds):
        writer.write(breed)

00:01 Writing to files.

00:05 Files can be open for writing using "w" as the mode, as seen here. However, this needs to be used with caution, as opening a file in this mode will overwrite any previous file, deleting the contents.

00:20 So be careful when using it. But with that in mind, let’s see that in action. Here you can see the code we’ve seen before, with open('text_file.txt'), now with the 'w' mode applied, as file:.

00:37 But in this indented block, we need to apply some code which Python will read, otherwise an error will be generated. So although we’re going to do nothing to the file, we are going to put a print() statement which says that the file is open.

00:50 This is purely to stop an error being generated. We’re not actually doing anything to the file object. Now, here we can see our text file. We can see it has those three lines in it, and if we run our writing.py file, it tells us the file has been opened. That’s just the print statement.

01:07 And now if we look, the text file is empty, and the contents had been erased. So this does need to be used with care. However, let’s move on to filling the file with something we want to.

01:19 The first method we’re going to look at is the .write() method. It’s used to commit a single string to an open file, as seen here. So once the file is open, we use .write() with the content we wish to write to the file.

01:32 Before you see any code examples, a quick word about line endings. If you’re using Windows, you’ll need to use \r\n at the end of each line, whereas on macOS or Unix you’ll need just \n.

01:46 Most of the examples given here have been done on Mac and you’ll see \n, but you’ll need to adjust depending on which platform you’re working on.

01:55 You may find this affects you if you’ve downloaded files from an unknown source or you’re dealing with people who are working on a different platform. Generally, it’s not too difficult.

02:04 It’s just something to keep in mind when you’re carrying on with these examples. Now you’re going to see that in action. So here, the content variable has been created.

02:14 As you can see, 'Some text for my text file' with an appropriate line ending.

02:23 And next, the .write() method is going to be used to write that content to the file.

02:31 Just save that file and then execute it.

02:39 Looking in the text editor, we can see it’s appeared: Some text for my text file. We’re on line 2, because we put a newline (\n) in.

02:47 The .write() method can be used multiple times on the same file while it’s open, so here you can see there are two .write() statements with different content in, but they’re all inside that context manager.

03:00 Now you can see that in action. The same code we’ve just seen, so we can add additional

03:12 with some text and a line ending on. And again, file.write(), but this time putting in the additional variable to put that data to the file.

03:23 And once that’s run, we can look in the text editor and see that data has also been written to the file already.

03:38 .writelines() allows multiple strings to be committed to an open file at the same time. We pass it a list of strings and then use the .writelines() method to write all of those strings to the file in one go. Now you can see that in action.

03:56 The file is already open in our context manager, and now we add the content for the line 1, line 2, and line 3, all with their newline characters (\n) at the end.

04:14 Next, we use file.writelines() and pass contentthe variable—to it. Now those three lines will be written to the file. We can execute the script and then look at the text file, and we can see Line 1, Line 2, and Line 3. In exactly the same way as we saw with .write(), the .writelines() method can be used multiple times on the same open file to add additional content, as seen here.

04:48 Reading from one file, writing to another. It’s possible to have a context manager with multiple files open in different modes, as we see here. We’ve got an input file as a source and an output file as a destination.

05:00 And now you can see this in action. So here, we’re going to open two files up. with open('moby_dick.txt'), downloaded from the Gutenberg project.

05:11 That is going to be our file_in file. And then continue on the next line with a backslash (\), we’re going to open 'moby_dick_caps.txt' in write mode as file_out.

05:27 So we’ve got two files open in our context manager. The content is going to be all of the contents of file_in using .readlines().

05:37 And then we’re going to iterate through that for line in content: and each line is going to be written to file_out.

05:45 So we will have file_out.write() and we’re going to use the string method line.upper() to capitalize that. Once that’s saved, you can run it in the terminal.

06:03 And switching to our text editor shows us it’s all been capitalized. All of that has been done in a fraction of a second. Imagine how long it would take you to do that if you had to do that manually.

Avatar image for reblark

reblark on Aug. 12, 2019

If I wanted to practice this, how would the code find the file I entered?

Avatar image for LJIN Lab

LJIN Lab on Aug. 13, 2019

@reblark Python will automatically look in its root directory (the folder that your .py file is in). If the file exists in the root directory, it will open the file, but if the file does not exist, it will create one for you.

Avatar image for jamesbrown68

jamesbrown68 on May 2, 2020

On my Windows 10 machine, a ‘\r\n’ is not necessary to write to a text file. Just a ‘\n’ or a ‘\r’ was all it took.

Avatar image for khurram703

khurram703 on June 12, 2020

on my windows 10 machine, we only need ‘\n’ to move to the next line but in the video, it is mentioned ‘\r\n’. Is there any subtle difference?

Become a Member to join the conversation.