Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Getting Input

00:00 In the previous lesson, I showed you output with the print() and format() built-in functions. In this lesson, I’ll be going in the other direction, getting input.

00:09 The two most common places for getting input for your program are provided as built-in functions. You can ask a user for input or read from a file. Let’s go see how these work.

00:21 It’s kind of hard to demonstrate the built-in functions without using any of the built-in functions, and that’s why you’ve already seen input when I showed you iter(), or you have if you’ve taken the lessons in order at least.

00:34 Like print(), this is usually one you experience early when learning Python. A good second exercise after “Hello World” is asking the user for some info like their name or age. There isn’t much deeper to input than the basics. There really aren’t any tricks to show you, but the course wouldn’t be complete without it, so I’ll touch on it quickly.

00:55 input() on its own gives you a blank line where you can type something.

00:59 The function then returns what you typed. Here, the string Hello. input() optionally takes an argument.

01:09 The argument gets used as a display prompt. If you’re in the REPL and using 3.14 or later, you even get color highlighting of the prompt.

01:20 Rather than ask for input from the user, a common source of data for your program is to read a file. Python’s built-in open() function gets you access to a file handle, allowing you to read or write to the file.

01:33 Let’s start by writing to a file.

01:41 Here, I’ve used the with keyword to create a context block. You can use open() without one, but doing it this way is the best practice.

01:49 When you call open() through with, the as argument names a variable, which is where the file handle gets put. I’ve named my file handle file.

01:59 I’m passing two arguments to open(). The first is the name of the file to open, fruit.txt, and the second is the file mode. A w for the mode indicates that I’m writing to the file.

02:15 The file handle is an object that allows you to interact with the file. The .write() method sends the content you give it to the file. When the with block closes, you get the return result, which is the number of bytes written to the file. Note that \n is one character in case you were counting up the content there.

02:35 Normally, I teach reading from files first, but by doing writing first, I’m ensuring there’s a file to read from. Let’s read the content back in. This time, I’ll do it the old-fashioned way from way back times before context managers existed.

02:48 Kids don’t know how lucky they have it these days. Similar idea, but this time I’m calling the function directly. The return value from open() is the file handle.

02:59 The default file mode is reading, so although I could have used an r, leaving the mode argument off is good enough, and it’s the most common way to do it.

03:10 Looking at the file handle, you’ll see that the file was recognized as text. The handle also has the name of the file, the mode, and the character encoding of the file.

03:20 Let’s read the content.

03:22 You probably could have guessed there was a .read() method to go with the .write() one.

03:27 When you’re done with a file handle, you should always remember to close it.

03:31 File handles are a resource your operating system tracks, and there are limits as to how many you can have at a time. If your program exits, the OS will close the file for you, but doing it intentionally is best practice. This is why I prefer to use a context manager block.

03:47 It automatically closes the file handle when the block exits, meaning one less thing for you to remember. In the previous lesson, when I covered print(), I mentioned that there was one argument that I would skip until later.

04:00 Well, now it’s later. When calling print(), you can give it a file handle, thus directing the output. Instead of using file.write(), you can use print().

04:14 Same context manager as before,

04:18 but when I’m printing dog, I’m passing in our file handle,

04:24 and then cat as well. Let me read that back in.

04:36 And there you go. When you print to the screen, you are using a file handle as well. This is known as standard out, and it’s the default value of the file argument in the print() function.

04:47 You can get at the standard out file handle directly in the sys module.

04:58 Nothing special here. I’m just being explicit about where the output is going, which is the same as the default. The companion to standard out is standard error.

05:12 I know it doesn’t look any different, but it is. And yes, I was listening to rap music when I wrote this bit. The standard error stream also gets output to your terminal, just like standard out, but it uses a different mechanism.

05:27 On Unix systems, when you capture the output from a program, you can actually capture standard out and standard error separately. This can be handy, because if you’re capturing the output of a program, the error messages could still be put to the screen if you like.

05:43 In the interest of time, I only showed you the two most common arguments to the open() function, but it does take a few more though. You saw me use a string to indicate the name of a file.

05:53 You can also use path-like objects, like those from pathlib. You can also do something fancier, passing in a file descriptor. That’s for things like sockets.

06:04 Unix treats most input and output systems as file handles, so there’s lots of choice for descriptors here. Plain old text is definitely the most common of them though.

06:14 I showed you read and write modes. There are others as well, and I’ll give you a full list of those in a second. You’ll recall from our conversation about print() that Python buffers content before sending it through to the screen for efficiency reasons.

06:29 Same goes when reading and writing files. You don’t want to do it a character at a time. It’s not very smooth. Instead, you’re going to do it in chunks. The buffering argument gives you some control over this.

06:42 Setting it to 0 turns buffering off. Setting it to 1 buffers based on newlines, but that only works when reading text files. The default value of -1 tells Python to use a buffer size appropriate for your operating system.

06:57 Or finally, any other positive integer specifies the size of the buffer to use.

07:03 Text is a special case of binary data where the data is translated based on an encoding method. You saw a bit of this when I talked about characters where ASCII capital A is 65.

07:13 The encoding argument allows you to set what encoding to use when reading or writing a text file. The default value here is None, meaning to use whatever the operating system prefers.

07:25 On Unix systems, that’s typically UTF-8. The errors argument says what to do if there is an error during encoding. These support the same values used by the chr() built-in function, like strict and ignore.

07:39 There are some extra ones as well, but I leave it to you to look them up if you’re curious.

07:44 Newlines are tricky things.

07:46 \n actually translates to different character codes depending on your operating system. Some OSs just use \n on its own. Others differentiate line return from line feed and treat them as separate characters.

07:59 This can result in all sorts of wacky fun when reading text. The newline argument allows you to specify what to translate newline characters into.

08:09 You can’t use just anything here. It has to be one of the recognized combinations of newlines, line returns, or line feeds. The default value is None, which says to use the operating system’s preferred mechanism.

08:22 Remember when I said that Unix systems treat a lot of things like files, and you can get at a file descriptor object for sockets? Good times. Well, if you’re opening a file descriptor rather than a regular old file name, you can optionally specify that the descriptor doesn’t get closed when the file handle is closed.

08:40 This allows you to get rid of the file handle returned by open() without closing the thing it is pointing to. This only gets used for some special programming.

08:48 It’s not very common.

08:50 And speaking of, the opener argument allows you to reference a callable responsible for opening the file. Again, this is for very advanced usage.

08:59 I’ve never actually seen it in practice in Python code myself.

09:04 I demonstrated reading and writing to a file, but there are other supported modes as well. Again, r for read and w for write, but let me actually be a little more specific.

09:16 w means writing to a file that truncates first if it already exists. So if you write to a file that is already on your hard drive, the existing file gets replaced with the new content.

09:28 X going to give it to you. See, I told you I was listening to rap. Sorry, I’ll try to stay focused. x is like w, but if the file exists already, instead of overwriting it, it throws an error.

09:40 This is handy to avoid accidental overwrites.

09:43 a is for append. It writes to the file, but after any existing content. + allows you to both read and write to a file. You have to be careful with this and know where your file pointer is pointing to in the file at any given time, or you can overwrite stuff that’s already in there.

10:01 Again, a more advanced kind of thing. The last two don’t get used on their own. They’re combined with other modes. b is for binary and t is for text.

10:11 And both of these get combined with the others to specify what kind of work is being done. So for example, wb means write truncating binary data.

10:23 I know I said input is pretty straightforward, but if you do want to dive a little deeper, this course also talks about handling errors when users type the wrong thing, how to convert between types using built-in functions, of course, getting secret input, and using the third-party library pyinputplus for doing more interesting input things.

10:45 If you’d like to learn a bit more about some of the other modes and dealing with binary data, this course and tutorial. Next up, I’ll start a new section. This one is about classes, objects, and attributes.

Become a Member to join the conversation.