The project I'm currently working on has an inexplicable error, which either I'm too dumb to figure out, or is just that obscure and technical.
I'm trying to first locate a directory, returning the path to it, and then checking if a sub-directory exists within it.
from pathlib import Path
from os.path import isdir
from os import getenv
from subprocess import Popen
def find_dlDir():
example_dlHomeDirs = [
Path(getenv("HOME"), 'downloads'),
Path(getenv("HOME"), 'Downloads'),
]
if dlHome := getenv("DOWNLOADS_HOME") != None:
return dlHome
else:
for path in example_dlHomeDirs:
if isdir(path):
return path
return None
def dirExists(dirName: str):
if dlHome := find_dlHome() != None:
if isdir(Path(dlHome, dirName)):
return True
else:
return False
else:
print("No Downloads Folder found.\nTo resolve, create a new folder in \
your home folder with one of the following names:")
[print(name) for name in ['downloads', 'Downloads']]
exit(1)
def mkdir(path: Path, dirToMake: str):
"""
Make a directory with the name <dirToMake> at <path>
kwargs["path"]? Parent directory of <dirToMake>
kwargs["dirToMake"]? Name of the to-be-made directory
"""
Popen("mkdir", f"{str(path)}/{dirToMake}")
if __name__ == "__main__":
dir = "example"
if not dirExists(dirName=dir):
mkdir(path=getenv("DOWNLOADS_HOME"), dirToMake=dir)
The following code should-- with the filesystem below-- run: mkdir $HOME/Downloads/example
.
/Users/dickssau000 ¬
----Downloads ¬
--------github.com
--------youtube.com
--------mega.nz
Instead, I get a traceback:
Traceback (most recent call last):
File "/Users/dickssau000/.local/src/github.com/Saul-Dickson/dl/test.py", line 48, in <module>
if not dirExists(dirName=dir):
File "/Users/dickssau000/.local/src/github.com/Saul-Dickson/dl/test.py", line 24, in dirExists
if isdir(Path(dlHome, dirName)):
File "/usr/local/Cellar/python@3.9/3.9.1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/pathlib.py", line 1071, in __new__
self = cls._from_parts(args, init=False)
File "/usr/local/Cellar/python@3.9/3.9.1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/pathlib.py", line 696, in _from_parts
drv, root, parts = self._parse_args(args)
File "/usr/local/Cellar/python@3.9/3.9.1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/pathlib.py", line 680, in _parse_args
a = os.fspath(a)
TypeError: expected str, bytes or os.PathLike object, not bool
I'm absolutely sure that on line 24, the variables dlHome and dirName are os.PathLike and str respectively. Neither of those variables should have the type of bool, and I'm completely stumped on how to fix it. Does anyone have a clue as to what's going on here?
python: 3.9
if dlHome := find_dlHome() != None:
...
This is equivalent to
if dlHome := (find_dlHome() != None):
...
meaning dlHome
is of type bool
, not the result of find_dlHome()
! You want this instead:
if (dlHome := find_dlHome) is not None:
...
(you should also do None
checks using is
/is not
instead of ==
/!=
)