Once you’ve opened up a file, you’ll want to read or write to the file. First off, let’s cover reading a file. There are multiple methods that can be called on a file object to help you out.
At some point in your Python coding journey, you learn that you should use a context manager to open files. Python context managers make it easy to close your files once you’re done with them:
with open("dog_breeds.txt", "r") as reader:
print(reader.read())
results in
Pug
Jack Russell Terrier
English Springer Spaniel
German Shepherd
Staffordshire Bull Terrier
Cavalier King Charles Spaniel
Golden Retriever
West Highland White Terrier
Boxer
Border Terrier
Here’s an example of how to read 5 bytes of a line each time using the Python .readline() method:
with open('dog_breeds.txt', 'r') as reader:
>>> # Read & print the first 5 characters of the line 5 times
>>> print(reader.readline(5))
>>> # Notice that line is greater than the 5 chars and continues
>>> # down the line, reading 5 chars each time until the end of the
>>> # line and then "wraps" around
>>> print(reader.readline(5))
>>> print(reader.readline(5))
>>> print(reader.readline(5))
>>> print(reader.readline(5))
results in:
Pug
Jack
Russe
ll Te
rrier
Here’s an example of how to read the entire file as a list using the Python .readlines() method, which is likely the most useful method- for example we can get a list of strings that we could process into a dict- we can see this later
f = open('dog_breeds.txt')
f.readlines() # Returns a list object
results in a list of str:
['Pug\n', 'Jack Russell Terrier\n', 'English Springer Spaniel\n', 'German Shepherd\n', 'Staffordshire Bull Terrier\n', 'Cavalier King Charles Spaniel\n', 'Golden Retriever\n', 'West Highland White Terrier\n', 'Boxer\n', 'Border Terrier\n']
Once we have this file data imported, we can do operations on it, creating information from the data such as averages, counts, graphs, sub-sets of data and so on.
The with statement initiates a context manager. In this example, the context manager opens the file and manages the file resource as long as the context is active. In general, all the code in the indented block depends on the file object being open. Once the indented block either ends or raises an exception, then the file will close.
If you’re not using a context manager, then you might explicitly close files with the try … finally approach:
try:
file = open("hello.txt", mode="w")
file.write("Hello, World!")
except:
print("File could not be opened...")
finally:
file.close()
The finally block that closes the file runs unconditionally, whether the try block succeeds or fails. While this syntax effectively closes the file, the Python context manager offers less verbose and more intuitive syntax. Additionally, it’s a bit more flexible than simply wrapping your code with try … except ... finally.
Now let’s dive into writing files. As with reading files, file objects have multiple methods that are useful for writing to a file.
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)
Once we de-dent, the file handler is closed, but we can still work with any data that was read and stored by our program.
Sometimes, you may want to append to a file or start writing at the end of an already populated file. This is easily done by using the 'a' character for the mode argument:
with open('dog_breeds.txt', 'a') as a_writer:
a_writer.write('\nBeagle')
When you examine dog_breeds.txt again, you’ll see that the beginning of the file is unchanged and Beagle is now added to the end of the file:
with open('dog_breeds.txt', 'r') as reader:
print(reader.read())
will result in:
Pug
Jack Russell Terrier
English Springer Spaniel
German Shepherd
Staffordshire Bull Terrier
Cavalier King Charles Spaniel
Golden Retriever
West Highland White Terrier
Boxer
Border Terrier
Beagle
You can imagine that this might be useful for a "high_scores" file for a game, or logging activity, or any number of other uses.
It is important that when opening files for read/write operations, that the file is closed afterwards- using the context manager takes care of this for you.
The close() function closes the file and frees the memnory space acquired by that file. It is used at the time when the file is no longer needed or if it is to be opened in a different file mode.
# Opening and Closing a file "MyFile.txt"
# for object name file1.
file1 = open("MyFile.txt","a")
file1.close()