Search code examples
pythonpathcwd

attempt to creat a new directory in Downloads finishes to creating a new "~" in the cwd


So I am working on a script for myself in python to download works from Ao3. I have this setup file

{
    "username": "username",
    "password": "password",
    "downloadsPath": "~/Downloads/ao3",
    "format": "epub"
}

my problem is with the download path variable. in my scrip I do the following:

def main():
    setup = openJson(os.path.join(os.path.dirname(__file__), "setup.json"))
    os.makedirs(setup["downloadsPath"], exist_ok=True)

to make sure the destination for downloads exists. except that rather than creating the ao3 folder in /home/user/Downloads/ it creates a new ~/ folder in the CWD so something like /cwd/~/Downloads/ao3

I have no idea why it started doing this because before I started to do the rest of the script everything was fine but after a day of working on the script this behaviour started.


Solution

  • As I said in a comment, makedirs() doesn't automatically handle expansion of a folder named ~ to the user’s home directory, however you can easily do it yourself via os.path.expanduser() as illustrated below:

    import os
    
    setup = {
        "username": "username",
        "password": "password",
        "downloadsPath": "~/Downloads/ao3",
        "format": "epub"
    }
    
    downloadsPath = os.path.expanduser(setup["downloadsPath"])
    print(downloadsPath)
    os.makedirs(downloadsPath, exist_ok=True)
    

    You can also do something similar using the object-oriented pathlib module (which I highly recommend learning and using):

    from pathlib import Path
    
    downloadsPath = Path(setup["downloadsPath"]).expanduser()
    print(downloadsPath)
    downloadsPath.mkdir(parents=True, exist_ok=True)