So far all our inputs have been provided either by a human interaction with the command prompt or via human configuration at the command line.
This is okay for a small amount of input, but what happens if we want to input a large amount of data or provide data produced by another computer. In this instance, we need to know how to input data from a file as an external source. In this scenario maybe we are passing in a section of text that we want to translate, but typing it by hand would be impractical.
The open function is a built-in function. The documentation shows that there is an optional mode that can be passed in. In the example below we pass in r. This indicates that the file is opened as read-only. To write to the file you need to use w.
To get input from an external file we use the format
with open(filename, 'r' ) as variable_name:
<Do something with the variable here>
In lab_5_step_3_input_text_file.py type or copy the code below:
with open(file, 'r') as f:
text = f.read() #We use read() to read the actual contents of the file
In text.txt type or copy the following (or provide a sentence):
"The Quick Brown Fox"
To run the program, enter the following command in the terminal:
It should return the text from text.txt
Congratulations, you can now read input from a file. In the next part, we will look at a format called JSON. This is used a lot by computers to exchange information.