Creating Directories and Files (Recap)
In the past couple of lessons, you learned how to create directories and files using Python’s
pathlib module. You used the method
.mkdir() to create a directory, and here you also learned about two parameters, one being
exist_ok, which you can set to
True so that if the directory already exists, Python doesn’t throw an error. The default value of
False, so if you don’t set it explicitly to
True, Python will throw an exception if the directory already exists. Then you also got to know
parents, which is another parameter that is by default
False, but if you set it to
True, Python will create any missing parent directories that are in between the directory you want to create and whatever directory exists.
Often these two are combined, so that you would call
.mkdir() passing both
exist_ok=True as well as
Then you also learned how to create files, and you do that using
.touch() method doesn’t raise an error if the file already exists, and you also can’t pass a
That doesn’t exist on the
.touch() method, so all the parent directories containing the file must already exist for
.touch() to succeed.
You also learned how to combine certain attributes, such as
.parent together with
.mkdir() to then create subdirectories that might not have existed before, based on a path of a file that maybe doesn’t exist right now.
01:28 If that sounded confusing, then go back to the previous lesson and rewatch it. All right, so now you know how to create directories and files, and in the next lesson you’ll get started to figure out how you can iterate over directories and display the contents of those.
Become a Member to join the conversation.