简体   繁体   中英

error in relative path and absolute path in import

I have following folder structure

Tool -> Tool folder have following three subfolders
    inputfiles
    outputfiles
    soucefiles

sourcefiles have following files
       __init__.py
       main.py
       ParseLogFile.py

Following are contents of ParseLogFile.py

    class ParseLogFile:
        # initialize file name
        def __init__(self, filename):
            self.filename = filename
            return


def ParseLogFileFunc(self):
    print("ParseLogFileFunc called " + self.filename

)

Following are contents of main.py

from sourcefiles.ParseLogFile import ParseLogFile

parseFile = ParseLogFile("logfile")
parseFile.ParseLogFileFunc()

If i use following then it is working

    from ParseLogFile import ParseLogFile

parseFile = ParseLogFile("logfile")
parseFile.ParseLogFileFunc()

but I am trying to understand absolute and relative paths for import

Question 1:

When i gave absolute path like above i am getting followoing error

 from sourcefiles.ParseLogFile import ParseLogFile

If i run above file ie, main.py i am getting following error.

ModuleNotFoundError: No module named 'sourcefiles'

How do we rectify this error using abolute path?

Question 2:If i use relative path

from .ParseLogFile import ParseLogFile

parseFile = ParseLogFile("logfile")
parseFile.ParseLogFileFunc()

If i run above file ie, main.py i am getting following error.

ModuleNotFoundError: No module named '__main__.ParseLogFile'; '__main__' is not a package

Question 3: How do open a file by providing relate path in python for example in my case input file in "inputfiles" folder.

I am new to python and trying to learn python in realistic way used in real projects. Kindly help. I am using python 3.x and spyder tool of anaconda for development

Q1 & Q2 can be answered by one explanation. - you "main.py" and "ParseLogFile.py" are in same that's why just direct from import works as you might already know but when you gave relative path from you side it might be correct but python takes in another way around so in case of relative or absolute path always give using os lib in python. Hardcoding the path create problems most of the time.

Q3 import os dir_path = os.path.dirname(os.path.realpath( file ))

or you can get the absolute path in the same way.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM