Input from the Command Line and Files with Python 3

Introduction

So far we’ve been covering how to print messages to the console. This is useful for displaying information to your user and logging what is happening in your program. Sometimes you need to receive input from the user as well. Again we will revisit the example of a video game. Last time we made the user’s name a variable, but we still hard coded it in the program code. Let’s look at how to ask the user to enter their own name, and then store it in a variable.

Learning Goals

In this post we will cover two main methods of getting data into our programs. The first method will be prompting the user to type text. The second will be reading data from a file. We will cover some examples of both, and try an exercise at the end that combines them.

Prompting for User Input

The most basic form of user input is typed text at the command line. Python has a built in function for prompting the user with a message and then listening for the answer. This function is the input() function. The input function takes one argument when you call it. This argument is the text prompt to display to the user.

Create a new file called input_part1.py and add the following code to it:

When you run the program, you should see the following:


$ python input_part1.py
What is your name? Josh
Hello, Josh. Get ready to start!

Notice a few things about this output. First, the prompt provided to the input function starts letting the user type immediately at the end of the prompt string. So, to make it look nicer, we’ve added a space at the end of the prompt. If we wanted to type on a new line, we could have used \r\n instead of a space. \r\n is a special code which indicates a carriage return/newline in text.

Second, we stored the result of the input function in a variable called player_name. This works just like it did in the previous lesson, except instead of the variable being hard coded in the program, it is filled in when the program is executed (at ‘runtime’).

Third, the input function is smart about newlines. As soon as the user presses Enter, the text is captured and input strips off the trailing newline (‘Enter’ key) before storing the value in the variable. So, when you interpolate the message in the next statement, everything appears in a single line.

What if you want to capture multi-line text? Well, you can repeatedly listen for input using some looping logic, which we will cover in a later lesson. For now, just know its possible!

Loading Input from a File

Now we will look at how to read data out of a file to use in our programs. Reading data from a file can be very useful because it allows us to persist information across multiple runs of our program. For example, in our game, if we want to display high scores, we could store these in variables. However, when the program ends, the values in the variables are lost. If we store the high scores in a file, we can keep track and display them across multiple runs of our program.

To read a file we need to start looking at Python code blocks. Python uses a special method of indentation to indicate code that is grouped together into a block. These are called compound statements. The particular one we will be using is the with statement.

Create a text file in Sublime text called sample.txt and place the following code in it:

Next, create a new file called input_part2.py and add the following lines:

There is a LOT happening in these three lines. Lets break this compound statement down and understand what is going on.

  1. Line 1: with is a special keyword that indicates this is the beginning of a compound statement. open('sample.txt') loads the file we want to access for reading. as file is called the context manager. file will act as a sort of temporary variable referencing the file we’ve just opened. Also note, compound statements in Python 3 end the line with a colon!
  2. Line 2: First we tab indent to indicate this line is part of the compound statement. Next, the file’s readlines() function is used to read all the data from it. This data comes back as an array of strings, and is stored in the variable lines.
  3. Line 3: Again, we tab indent, because we are still in the compound statement. Next, ''.join() is a special function that combines an array of strings into a single string for printing. The empty quotes ” indicate what character is used as spacing between the array elements. You could use anything here that best suites your goals, but since our file is already formatted, we simply use empty string (ie, we don’t need a seperator for join in this instance). After joining the array into a single sting, the value is printed using print, like we are used to.

Note: An array is a special variable type that stores multiple variables in it. In this example, lines is an array variable of strings. Each individual string is called an element in the array, and holds one line of text from the file we read.

When you run the program, you should see the following printed:


$ python input_part2.py
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Combining User Input and File Access

For a good exercise, lets put everything together. Write a program that prompts the user for the name of a file, opens the file, and prints the contents.

You can find one possible solution in the files linked below:

questions.txt
high_scores.txt

Conclusion

We’ve covered two methods of capturing data for our application. One is interactive, prompting the user to type text. The second is loading data from a file. Both will be useful in upcoming lessons as we expand on our game example.

But before we do that, try telling your program to open a file that does not exist. What happens? We will cover some basic debugging and error handling techniques in the next lesson.