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
actually created a
.txt file. Let’s double-check that this is actually a file,
and there it is. If I use
.is_file() on the
Path object, then I get a
True. So I just created file called
If you call
.touch() again on an existing file, then it doesn’t raise an error like it does with directories that already exist. So I can do this, and there’s no penalty for me.
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.
If I tried to create
too_much_future_path inside of a directory that doesn’t exist, let’s say inside of
"notes" / and then I will create a path that doesn’t exist. I’ll say there’s a
"yearly" folder, but I’ve never created this one.
And then inside of
too_much_future_path—oh, I forgot to put a file on there, so let me add that.
I’m just going to overwrite the variable here to also add a filename,
So now the
too_much_future_path is here, and the path points to a file called
3033.txt inside of a folder called
yearly. However, that
yearly folder doesn’t exist.
So if now I tried to create this file by saying
.touch(), Python will give me a
FileNotFoundError. The reason for this is that
yearly, this folder, just doesn’t exist.
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 since there’s only one directory missing, this one, you can say
too_much_future_path.parent. This will point to the
Path object that goes to the subfolder
yearly, and I can say
Optionally, if there were multiple directories that didn’t exist in between here, you could pass
parents=True, and then after calling this function, you can say
03:40 And now it went through. This file was created as well.
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.