path = '~/.config/remind_task/tasks.yml'
dir_name = os.path.dirname(path)
os.makedirs(dir_name, exist_ok=True) #Dig if the upper directory does not exist
with open(path, mode="w") as f:
f.write("hoge")
If you open the file and create it like this, you will think that the file will be created in .config/remind_task/tasks.yml
in your home directory.
Executing the above code will create the file. But not.
> cat ~/.config/remind_task/tasks.yml
cat: /Users/atu/.config/remind_task/tasks.yml: No such file or directory
But the file has been created. As a result of searching around where it was, it was created in the current directory.
In this case it was in /Users/atu/Documents/python/remind_task/~/.config/remind_task/tasks.yml
.
> cat "/Users/atu/Documents/python/remind_task/~/.config/remind_task/tasks.yml"
hoge
If you want to handle a path that starts with a tilde, you can do as follows.
import pathlib
path = pathlib.Path("~/.config/remind_task/tasks.yml").expanduser()
print("path", path)
## path /Users/atu/.config/remind_task/tasks.yml
Recommended Posts