Python for Absolute Beginners Transcripts
Chapter: Reading and writing files in Python
Lecture: Concept: Appending a line to a text file
0:00 Let's just quickly review our simple little log thing.
0:03 Where we were able to write out some kind of message
0:07 and append it to a text file
0:09 that is just line by line interesting.
0:11 So we wrote this log function
0:13 it takes some kind of text
0:14 and we use our os path to come up with the absolute path.
0:18 And then we come up with some form of time text.
0:21 Here we're using this string format time.
0:22 Which gives us actually, a better output
0:24 than what I was doing.
0:25 Then, we're just going to use our open method
0:28 inside of a width block
0:30 get a output file stream out.
0:32 I name it so it reminds me
0:33 yes you can write this but not read from it
0:35 or read from it, but not write to it
0:38 based on how you opened it.
0:39 Cause the functions are there for both.
0:41 But depending how you open it
0:42 one of the other is available.
0:44 But the most important thing here
0:46 is that we used a to append
0:48 rather than w to overwrite.
0:49 And then we just write out parts of text
0:52 and it piles up all in one line
0:54 so we'd write the time text
0:55 then we'd write out the message
0:57 that they're actually trying to log.
0:59 So they don't have to worry about the timing.
1:01 And then we say
1:02 that's the end of this line
1:03 wrap it around, so that the next time
1:05 we try to log to it it starts on a line below.
1:08 And that's it. And here we're also printing the message.
1:10 So you can both log to it
1:12 everything that goes to the screen, basically
1:14 will also go to the file.
1:16 If you wanted.
1:17 We did ours a little bit different in the demo.
1:19 Not too hard, it reuses a lot of the same ideas.
1:22 But very very cool, and quite easy to do.