0

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.

julia
  • 139
  • 3
  • 11
  • 1
    It appears that `makedirs()` simply doesn't consider a folder named `~` to be anything special — so you will need to translate it yourself with [`os.path.expanduser()`](https://docs.python.org/3/library/os.path.html#os.path.expanduser). – martineau Jun 29 '21 at 22:33
  • Thank you is works now. i ended up doing composing `expanduser` and `expandenv`. could you post your comment as an answer so i can flag it as the solution? – julia Jun 30 '21 at 06:39
  • You're welcome and thanks for the offer. I've never heard of `expandenv`, perhaps you meant `expandvars`. – martineau Jun 30 '21 at 09:53
  • yea sorry it's `expendvars` – julia Jun 30 '21 at 10:19

1 Answers1

1

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)
martineau
  • 119,623
  • 25
  • 170
  • 301