问题
I've been "fighting" with absolute and relative paths in Python for a while and I know that there are quite a few questions on this topic, but I couldn't find an answer to my particular problem.
Given the following project structure:
package/
subpackage1/
moduleX.py
moduleY.py
subpackage2/
moduleZ.py
folder1/
file1.txt
I am importing in moduleX.py
a function from moduleZ.py
which requires information stored in file1.txt
to work. I have no problem importing the function from moduleZ.py
, however since it requires file1.txt
I get the error message "No such file or directory".
My question is: When the function from moduleZ.py
tries to open file1.txt
after being imported which path does it consider?
I would like for it to work with a relative path, but I couldn't find a way for it to work.
Thanks in advance.
回答1:
My question is: When the function from moduleZ.py tries to open file1.txt after being imported which path does it consider?
It considers relative paths starting from the working directory of the person/process running the code.
One of the standard ways of finding data files is to note the directory name of the root of your package, ie. in package/__init__.py
:
DIRNAME = os.path.dirname(__file__)
then whenever you want to access a file:
from package import DIRNAME
file1_txt = os.path.join(DIRNAME, 'subpackage2', 'folder1', 'file1.txt')
回答2:
Have you tried to putting something like in the moduleZ.py to get the path you are currently in and then do the relative path from the variable you generate?
import os
mypath = os.path.dirname(__file__)
txtfile = os.path.join(mypath,folder1,file1.txt)
来源:https://stackoverflow.com/questions/59994911/opening-a-file-from-an-imported-function