Creating a File
Let’s create a file inside of that monthly directory. I want to make some resolutions for coming January. So let’s say I will create a
january_path file inside of the
monthly_dir, and I’ll call it
That’ll contain some aims for the coming year, let’s say. So I’ve created the path. The path is here, but the file doesn’t exist yet. Now, if I want to create the file, I can say
january_path.touch() … and this
Nothing happens really, except that the timestamp gets updated. Now, you can’t create a file inside of a path structure that doesn’t entirely exist. There’s no equivalent to the
parents=True attribute that you can use for directories.
You need to have all the containing parents folders created before creating a file. There is no
parents=True parameter that you can pass to the
.touch() method, but what you can do is you can use the
.parent attribute on the path to return a
Path object and then create that folder.
So by combining the attributes and methods that you have available on
Path objects, you can perform a lot of common files operations such as creating directories and creating files. In the next lesson, let’s do a quick recap of the different methods that you saw.
Become a Member to join the conversation.