DEV Community

Gavriel Linoy
Gavriel Linoy

Posted on

Directory Errors In Python

Directory Errors
Sometimes Python make issues with directories, so this is code skeleton to solve this issue!

import os

def main() -> None:
    print("Hello")

if __name__ == "__main__":
    abspath = os.path.abspath(__file__)
    dname = os.path.dirname(abspath)
    os.chdir(dname)
    main()
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
manhdt profile image
thitkhotau

I use pathlib. It it's like that "dbname = Path(file).parent". I think os.chdir() is very risk because it's change current folder. I think using contextlib to change current folder is safe more.

Collapse
 
gavriel770u profile image
Gavriel Linoy

Thanks for the comment!
I'll try to see if it works and research it :D