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?