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.
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, eg os.chdir("..")
to go up one folder etc.
To further elaborate the problem - i tried reproducing your situation:
src
(pure python, no venv, no welcome scripts)folder_one
and folder_two
folder_one
i created a text-file with a sample-text called my_file.txt
folder_two
i created a python file called sub_module.py
equivalent to your file.src
as the sources root (which is not necessary i think): In PyCharm project tree > rightclick src folder > mark directory as > sources rootsub_module.py
src
folderThen 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.
Did you try the entire path of the npy file?
It all depends on the current directory where your Python program is executed. If it starts from folder_two
, then you should open the file by going "up" one level: '../folder_name/numpy_file.npy'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.