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

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

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)

Comments & Discussion

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.

Become a Member to join the conversation.