Python 3, an Illustrated Tour Transcripts
Chapter: The standard library
Lecture: Walk-through: pathlib

Login or purchase this course to watch this video and the rest of the course contents.
0:00 In this video, we're going to look at path test, open that up in your editor. Let's run it and make sure that our environment is configured.
0:10 Okay, we have one error, we're not getting failure with importing pytest, so we're good there and we have one test function.
0:17 Let's go through this and figure out what's going on. The first part, get the contents of the current directory using the path module
0:24 store the results in cur, the variable called cur. So in Python 3, there is now a library called pathlib, and we can say from pathlib import path
0:40 and let's get the current module, current equals path and period should be the current guy. If you want the contents of that you say iterdir,
0:55 and that will give you what is in the directory. Let's run this and see if it works. Okay, so we're only getting one failure which is fine
1:09 because we have one test and we're getting an error on line 16. So it looks like the first guy worked.
1:16 So what iterdir does, given a path it gives you a sequence that has all of the results in it or all of the files and directories that are in that.
1:25 So our test is just saying is path test in the current directory, and because we're in that directory, it is. Cool.
1:33 Make a path with a file named test.txt, and store it in test file. So test file equals path, and we're going to say test.txt, that should work.
1:49 I'll just run it and see if it works. Okay, we're now on line 23, so we're down here. Write hello world to test file,
1:58 we can use this path guy as we would a result of an open in the context manager so I can say with test file and then I can call on that open
2:13 and I can pass in a mode, so I'm going to pass in the mode write and I'm going to say as f out: and I'll say f out.write, and we'll write hello world.
2:25 At this point, after we've exited from this, test file should exist, it should have a name and we should assert that hello world is in there.
2:35 Let's run it and make sure it works. Okay, we're now down to line 32, so we're at this last part. Delete the test file.
2:44 So we have test file, how do we delete it? There is no delete. Is there a remove? There is no remove. Is there an rm? There's an rm dir.
2:54 So none of those are the way to delete a file, the correct pronunciation of this is unlink. Let's run this and see if it works. Cool, we're good.
3:05 So hopefully, this gives you a brief chance to play around with path. You can get the contents of a directory by saying iterdir,
3:12 you can create a path, you can write to it by putting in a context manager
3:17 and calling the open method on it, rather than using the built-in open function and you can delete it if you want to as well.


Talk Python's Mastodon Michael Kennedy's Mastodon