我有以下文件夹结构
Tool -> Tool folder have following three subfolders
inputfiles
outputfiles
soucefiles
sourcefiles have following files
__init__.py
main.py
ParseLogFile.py
以下是ParseLogFile.py文件你知道吗
class ParseLogFile:
# initialize file name
def __init__(self, filename):
self.filename = filename
return
def ParseLogFileFunc(self):
print("ParseLogFileFunc called " + self.filename
)
以下是主.py你知道吗
from sourcefiles.ParseLogFile import ParseLogFile
parseFile = ParseLogFile("logfile")
parseFile.ParseLogFileFunc()
如果我使用了following,那么它就起作用了
from ParseLogFile import ParseLogFile
parseFile = ParseLogFile("logfile")
parseFile.ParseLogFileFunc()
但我试图理解导入的绝对路径和相对路径
Question 1:
当我给出如上所述的绝对路径时,我得到了如下错误
from sourcefiles.ParseLogFile import ParseLogFile
如果我在文件上方运行,即。,主.py我有以下错误。你知道吗
ModuleNotFoundError: No module named 'sourcefiles'
我们如何使用一个单独的路径来纠正这个错误?你知道吗
问题2:如果我使用相对路径
from .ParseLogFile import ParseLogFile
parseFile = ParseLogFile("logfile")
parseFile.ParseLogFileFunc()
如果我在文件上方运行,即。,主.py我有以下错误。你知道吗
ModuleNotFoundError: No module named '__main__.ParseLogFile'; '__main__' is not a package
问题3: 如何在python中提供相关路径来打开文件,例如“inputfiles”文件夹中的my case input file。
我是python的新手,尝试以实际项目中使用的方式学习python。请帮忙。我正在使用Python3.x和anaconda的spyder工具进行开发
问题1和问题2可以用一种解释来回答。 -“你”主.py“和”ParseLogFile.py文件“在相同的情况下,这就是为什么直接从import工作的原因,正如您可能已经知道的,但当您从您的角度给出相对路径时,它可能是正确的,但是python采用另一种方式,所以在相对或绝对路径的情况下,始终使用python中的os lib。硬编码路径在大多数情况下会产生问题。你知道吗
第三季度 导入操作系统 目录路径=操作系统路径目录名(os.path.realpath文件(文件)
或者你也可以用同样的方法得到绝对路径。你知道吗
相关问题 更多 >
编程相关推荐