Search code examples
pythonpycharm

Import data from files in same project in PyCharm?


This is a simple problem but I am struggling to solve it. I have a project open in PyCharm Community Edition 2021.1.1. I have a .npy file with data, and it's located at src -> folder_name -> numpy_file.npy. Then, I have a Python file under another directory in the same project, located at src -> folder_two -> python_code.py. In my Python file, I attempt to load the numpy file data using:

np.load('folder_name/numpy_file.npy')

but it tells me there is no such file or directory.

I have marked 'src' as my Sources Root. What else am I missing? Thank you.


Solution

  • Easiest is to check your current path with import os and print(os.getcwd()) and navigate from there - you might be in a different folder than you think. As far as i know defining a sources folder does not mean that this is your current working directory. You define such things in the run-configuration at Working directory. Also, with os you can change directories if that is what you want, e.g. os.chdir("..") to go up one folder etc.


    Edit

    To further elaborate the problem - i tried reproducing your situation:

    1. Created a new pyCharm project in a folder called src (pure python, no venv, no welcome scripts)
    2. I created the subfolders folder_one and folder_two
    3. Inside folder_one i created a text-file with a sample-text called my_file.txt
    4. Inside folder_two i created a python file called sub_module.py equivalent to your file.
    5. I defined src as the sources root (which is not necessary i think): In PyCharm project tree > rightclick src folder > mark directory as > sources root
    6. I created a run configuration:
      • Script path: path to your sub_module.py
      • Working directory: path to your src folder
      • The rest can be empty

    Then finally, this is the content of my sub_module.py file:

    print("Im in folder: " + os.getcwd())
    
    # Here i define which file i want to access - taking for granted we are in the src folder already
    other_file = "folder_one" + os.sep + "my_file.txt"
    
    # Here i check if the file really exists
    if os.path.isfile(other_file):
        
        # Here i do some operations with the file and demonstrate os.path.abspath, which is not even needed
        print("I can access file " + os.path.abspath(other_file))
        with open(other_file) as f:
            print(f.read())
    

    This returns me the content of my_file.txt. I also uploaded the zipped PyCharm project here (where i do not know if it is fully legal). Hope this helps to relate.