Search code examples
pythonpython-3.xpypi

Current working directory of PyPi package is root user folder? How to make cwd the package's directory?


I have a custom PyPi package. It is installed under Pyhon\Python38\Lib\site-packages\myCustomPackage.

In the __init__ code for myCustomPackage, I perform a few different directory operations, which failed to find the correct files and directories which reside in the Pyhon\Python38\Lib\site-packages\myCustomPackage folder.

I looked at the output of os.getcwd() and it showed the cwd to be C:\Users\TestUser, which is the root Windows user folder.

I would like the root folder to be the myCustomPackage folder.

For example, the file \myCustomPackage\__init__.py would contain

import os
class myCustomPackage():
    def __init__(self): 
        print(os.getcwd())

If I run:

from myCustomPackage import myCustomPackage
theInstance = myCustomPackage()

The output is:

C:\Users\TestUser

How can I change that to be C:\Users\TestUser\AppData\Local\Programs\Python\Python38\Lib\site-packages\myCustomPackage?

Note : I would want it to be dynamic. No hard coding, in case the python version changes or the Windows user changes.


Solution

  • To get the directory path of the current module, you can use the built-in __file__.

    To set the cwd to the module directory, use:

    import os
    import sys
    from pathlib import Path
    
    
    class myCustomPackage():
        def __init__(self):
            module_directory = Path(__file__).parent
            os.chdir(module_directory)
            print(os.getcwd())