Writing to Files8:00 with Kenneth Love
You often need to write to a file to store data for later use. Python makes this really straightforward!
open(filename, mode="r")opens a file. More info in the docs.
file.write("hello world") would write
"hello world" to whatever file the
file variable points at.
file.close() closes the pointer to the
The two most common modes or flags for writing are
"w", for truncating and then writing, and
"a" for appending to the file.
The context manager pattern for dealing with files is:
with open("my_file.txt", "a") as file: file.write("Hello world")
[MUSIC] 0:00 Hi, I'm Kenneth, the Python teacher here at Treehouse. 0:04 Quite often, when we're writing code, 0:08 we get the idea that we should put handy information into files. 0:09 Or just write things out to a file so we'll have it later. 0:12 I don't mean our scripts, of course. 0:15 Those are saved into files. 0:17 I mean things like, I'm going to ask the user how they're feeling today, 0:19 and then save it into a file. 0:22 Thankfully, Python makes this easy. 0:24 We only have to know one function to open the file, and 0:26 a couple of flags to control how it's opened. 0:28 Let's get over to workspaces to see how to do this. 0:30 Opening a file in Python is surprisingly easy. 0:34 But before we can read a file, we need to write a file, all right? 0:37 I want to write a script that will let me jot down reminders and notes and such. 0:42 Let's call it remember.py. 0:47 So let's make a new file, remember.py. 0:49 Alright, cool, and let's add in a def rememberer, and a thing to remember. 0:54 And we'll say open file, write thing to file, close file. 1:03 And our function has to do something so we'll just say pass. 1:09 And then let's say if name is equal to main 1:13 then run rememberer, and remember should get some input. 1:18 What should I remember? 1:24 So cool, there's that let's go ahead and run it. 1:28 And what should I remember? 1:33 I don't know remember the milk. 1:34 All right, so that's cool. 1:36 But we actually need to do the commented things, right? 1:38 So luckily Python gives us this function that's called open. 1:41 And so we can do like file equals open 1:46 database.txt and let's just try that, all right? 1:49 So we get the file open and 1:54 we've put it into this pointer, this variable, called file. 1:56 All right, so let's try running that. 2:01 And you should remember the milk. 2:03 That's a big exception. 2:06 What this exception tells me, is that I don't have a file named database.txt. 2:08 That's why we get the error. 2:14 We get an error because the file doesn't exist. 2:15 This a good time to talk about flags. 2:18 Pythons open function uses flags to tell it how to open the file. 2:20 Like we want to open it for reading, we want to open it for writing, 2:25 we want to open it for appending, and other ways. 2:28 By default, if we don't give it an argument, which is what we've done here. 2:33 Then, it opens it for reading and reading, kind of requires the file to exist, right? 2:36 Currently, there isn't a database.txt so Python can't open it. 2:43 So, let's add in the "w" flag. 2:48 W, for write. 2:52 Right? 2:54 So, Cool. 2:55 Let's run this again. 2:56 And I want you to remember the milk. 2:58 No errors. 3:00 Great. 3:01 All right, so now, let's see, let's refresh this over here. 3:01 And when you see that we have a database.txt, there's nothing in it. 3:06 That's fine, we didn't actually write anything to the file. 3:09 Let's do that now. 3:13 All right so, writing the files is really simple. 3:14 We do whatever variable points to the file and then we do a dot and 3:17 then we do write and then we do whatever it is we want to write that file. 3:23 So I'm going to do thing and then I'm gonna add in a new line character. 3:29 That way each thing gets to be put on to it's own line. 3:35 All right, so let's run that. 3:37 And again, let's say remember the milk. 3:41 And let's go look at database.txt. 3:43 And milk is in there and there's a new line. 3:46 So, cool, that's pretty neat. 3:49 That's the thing we wanted to be remembered, and it's in there. 3:51 It's important that we can remember more than one thing, right. 3:54 So, let's do that. 3:58 And I've already put in milk, so the other thing I need to remember is, 3:59 I need to remember to get orange juice. 4:03 So, I'm gonna put in orange juice. 4:06 And let's go check and make sure both those things are in our file. 4:08 Only have orange juice. 4:12 Our old record's gone and it's been replaced with a new one. 4:13 So, I wonder why that is? 4:18 Let's check the documentation and let's find out. 4:20 Let's go over here and look for open and there's open. 4:25 And let's look at these, these are the modes that I was telling you about. 4:33 So there's R for reading which is the default. 4:37 There's W for writing which truncates the file first. 4:39 Aha! See it truncates. 4:45 Truncates means it deletes everything out of the file. 4:47 It shortens the file down to 0 bytes. 4:49 There's nothing in the file, and then it writes. 4:53 Okay, that's not what we want. 4:56 This is why you read the documentation. 4:57 So A opens it, appends to be in the file if it exists. 5:00 Okay, that's that probably what we want. 5:05 We probably want A. 5:06 And again, this is why it pays to read the docs. 5:08 Alright, let's fix our script. 5:10 So come over here, we don't wanna open it with W, we wanna open it with A. 5:12 All right, so right now my database 5:15 file has orange juice in it, so I'm gonna add milk cuz I still need to get milk. 5:21 All right, so milk and let's come over here and look at database. 5:24 Sweet, there's orange juice and there's milk. 5:30 Everything is in there, and they each have their own line. 5:32 They're all in the file. 5:35 We need to do one more thing, we need to close the file. 5:37 Now if you're really building this, and 5:41 you're really building it the way that I'm building it, when this function ends, 5:43 when rememberer hits the end of it and it's done. 5:46 Then everything inside it gets garbage collected. 5:50 Python takes all that stuff and goes, you don't need this anymore, and 5:53 throws it away. 5:56 Which means that the file being open, the file would be closed. 5:57 So it would be fine, it would be garbage collected and then it would be closed. 6:01 But, I like being really explicit about this. 6:06 I don't want to know that I'm closing the file. 6:08 I want to make sure that file is closed. 6:10 Some I'm gonna do it on purpose. 6:12 So I'm gonna do file.close, not clone, 6:14 close and I know that the file has been closed. 6:17 So if I run this again, and 6:22 I need to pick up a sweater, I know the file's been closed. 6:23 Nothing changed outwardly, but Python opened the file, Python wrote to the file, 6:29 and then Python closed the file. 6:33 This pattern is really, really common, and it's actually so 6:36 common that there's a built in easier way to do it. 6:39 We can use the with keyword to make what's known as a context manager. 6:43 We're defining a block like a if or a while and inside of that block, 6:48 the variables only exist for a certain time. 6:54 If I come over here, and I say with, and 6:58 I take out the file equals, open that as file. 7:03 Now we have, inside here, we have a block. 7:07 Inside this block, the file exists and the file points to that opened file. 7:09 But once this block ends, file goes away, which is really awesome and handy. 7:14 So we're actually just going to indent both of those and since file 7:20 goes away once that with is done, I don't need those two lines anymore. 7:25 So all I need is, 7:31 open up the file In a context manager, write the thing into the file. 7:33 So, cool we have two lines that are replaced our three lines. 7:38 Let's run it one more time to make sure that it works. 7:41 I remember to get a sword and 7:44 if come look at my database, I have orange juice, milk, sweater and a sword. 7:47 And it's kinda funny that orange shows up like that. 7:52 Anyway, so great. 7:55 Now you know how to write to files. 7:56
You need to sign up for Treehouse in order to download course files.Sign up