Step 3 - Input from a file

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>
  • Create two new files:
    • lab_5_step_3_input_text_file.py
    • text.txt

In lab_5_step_3_input_text_file.py type or copy the code below:

def open_input(file):
    with open(file, 'r') as f:
        text = f.read() #We use read() to read the actual contents of the file
        print(text)

def main():
    open_input("text.txt")

if __name__=="__main__":
    main()

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:

    python lab_5_step_3_input_text_file.py

  • It should return the text from text.txt

What did python do?

  • Python used text.txt as an input parameter for the file.
  • It used with open() to open the file and r as read-only.
  • It used the .read() method to read the contents of the file and assign it to the variable text.
  • It printed the variable to return the sentence.

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.