0

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 i.e., 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 i.e., 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

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
venkysmarty
  • 11,099
  • 25
  • 101
  • 184
  • [How to do relative imports in Python](https://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python/73149) – Moses Koledoye Aug 16 '18 at 14:28

1 Answers1

0

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.

  • @ Junaid Ghauri. Thanks for response. Can you please elaborate what does you mean by python takes in another way around? – venkysmarty Aug 17 '18 at 05:16