Search code examples
pythonpython-3.xpython-os

Some functions in "os" package misbehaves when taking imported variables as arguments


I have a config file from which some values are being read using configparser, one of which is PROJECT_PATH
The config-reading happens in a separate python file which is imported to main.py
The aim is to list all the directories present in the PROJECT_PATH

To do that, I'm using os.listdir() which gives an error.

>>> os.listdir(PROJECT_PATH)
FileNotFoundError: [Errno 2] No such file or directory: '"/home/user/projects/"'

But, if I pass the path hardcoded, like: os.listdir("/home/user/projects") then it works correctly and shows the directories.

I also tried using os.path.exists() and similar problem occurs:

>>> os.path.exists(PROJECT_PATH)
False
>>> os.path.exists("/home/user/projects")
True

Now, the funnier thing is this:
When I'm creating a local variable say prj_path and storing the path value inside there, it works.

>>> prj_path = "/home/user/projects/"
>>> os.path.exists(prj_path)
True

However, if I store the imported variable PROJECT_PATH into a local variable, and use it, it doesn't work.
I also tried other things, like typecasting again str(PROJECT_PATH) and this also doesn't work.

Basically, any operation using the imported variable PROJECT_PATH DOESN'T work, but using only local variables, and/or hardcoded strings work!


I also tried using the pathlib module to generate path from string: pathlib.Path(PROJECT_PATH)
This also doesn't work.
No operations using the imported string works when passed to any of the aforementioned functions.


Solution

  • It looks like the double quotes are part of the value of the config variable loaded from the config file. This is suggested by the error message:

    FileNotFoundError: [Errno 2] No such file or directory: '"/home/user/projects/"'
    

    Remove the surrounding quotes from the path value in the config file, or strip them before use. I would prefer the former as that requires less corrective code.