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

Unlock This Lesson

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

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Writing to a File

Give Feedback

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():

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)

reblark on Aug. 12, 2019

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

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.

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.

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.