The File object: A brief introduction
The File object: A brief introduction#
Python uses a File object to enable you to read and write data from a file. Here’s a short example of this:
# The "w" option here indicates that the file is to be written. If the file already exists **it will be deleted**
# Be careful!
# Options are:
# "r": The file is to be read. It will not be possible to change anything in the file with this flag.
# "w": The file is to be written. If it already exists it will be deleted.
# "a": Open the file for both reading and writing. You *can* write to the file, but it will be written at the end
# of existing contents.
# "b": The "b" flag can be added to any of these "rb", "wb", or "ab". This indicates the file stores binary format
# data (not human readable).
file_pointer = open('example_file.data', 'w')
# The \n here indicates a newline. It's what the return key produces.
file_pointer.write("Hello\n")
file_pointer.write("World")
file_pointer.close()
This then leads to the question of “where exactly is this file “example_file.data”, which we’ve just created? We will demonstrate this for you.
Also note that used the \n character when we did .write("Hello\n") The \n character is special and it means “new line”. So if we do file_pointer.write("\n") it adds a new line to the file (same as having pressed the enter/return key). If we hadn’t included this, the file would read HelloWorld.
file_pointer = open('example_file.data', 'r')
for line in file_pointer:
# We need the strip method here to avoid the newline character being written twice!
print(line.strip())
file_pointer.close()
Hello
World
Equivalently we could write the following using the with statement. This is recommended because it ensures that the file is definitely closed outside of the with block. Forgetting to close a file can cause problems, so do this!
with open('example_file.data', 'w') as file_pointer:
file_pointer.write("Hello\n")
file_pointer.write("World")
with open('example_file.data', 'r') as file_pointer:
for line in file_pointer:
# We need the strip method here to avoid the newline character being written twice!
print(line.strip())
Hello
World
EXERCISE Write a file that contains the first 10 square numbers (1, 4, 9, …) and then read this back in and print it to the screen.
Hint: Remember the string formatting that we practiced last week? You can only write strings to a file, so you must convert these numbers to and from strings when reading/writing to a File. Don’t forget the newline character (\n)!
Hint: Remember how to use for loops with a sequence or ‘range’ of values. You may need to look over your notebooks from previous weeks for a reminder.
We note that in general many of python’s libraries contain file reading/writing utilities. We will explore utilities in numpy and pandas to do this in the coming weeks, which make storing and reading large datasets very efficient!
# Exercise solution goes here