The dataset for this course can be found in the file forex_rates.txt.
We will have to extract the contents from this file.
This lesson deals with reading data from files with Python.
Technically, a file is a region of space on a storage device, like a hard drive or USB.
Access to files is controlled by the operating systems (OS), like Windows, MacOS, or Linux.
A program must ask the OS for permission to access the file.
Python provides a very comfortable interface to the surrounding OS for file access.
As a programmer, you can ask permission to access a file with the function open().
my_file = open("data.txt", "r")
The first argument is the file name; the second argument "r" indicates that we intend to open the file in read-only mode.
The contents of a file opened in read-only mode cannot be changed.
Since we only need to read the contents, requesting write access by using "w" is unnecessarily permissive: we may be denied access to the file.
If access is granted, open() returns a file object from which can be read by calling the read() method.
contents = my_file.read()
A method such as read() is very similar to a function.
Functions act independently, but a method belongs to an object.
In this case, the method read() belongs to the file object my_file.
We call it by using the object access operator . (dot).
The method reads the file and returns its contents as one big string.
Thus, by doing contents = my_file.read() we read the file and store its contents in a variable.
Close the file once the contents are extracted with the close() method.
my_file.close()
If you wrote contents to a file and you do not close it properly, the file may get corrupted.
We can print the contents we read from the file now:
print(contents)