0

This is my directory structure

-directory1
  |-currentlyWritingCode
-directory2
  |-__init__.py
  |-helper.py
  |-view.ui

The helper.py is a UI from pyqt4 framework. It needs the view.ui file . it has following code to load the ui data

viewBase, viewForm = uic.loadUiType("view.ui")

now in directory1 in the currently writing code I did this

import directory2.helper

when I run the code in currentlyWritingCode it is throwing an error that

FileNotFoundError: [Errno 2] No such file or directory: 'view.ui'

What to do now?

using python3.5 from anaconda on Centos 7

srinath29
  • 345
  • 2
  • 4
  • 14

1 Answers1

1

Use os.path.join(os.path.dirname(os.path.realpath(__file__)),'view.ui') in place of view.ui. This will ensure you correctly reference the folder that the python file lives in, regardless of the code that imports it.

Note: Make sure you have import os with your other imports.

How does this work?

__file__ is an attribute of the module you are importing. It contains the path to the module file. See this answer. However, this path is not necessarily an absolute path. os.path.realpath returns the absolute path (it even follows symlinks if there are any). At this point we have a full path to the module, so we take the path to the directory (os.path.dirname) and join it with the original filename (which we assumed to be relative to the original module and so should be in the aforementioned directory). os.path.join ensures that the correct \ or / is used when constructing a file path so that the code works on any platform.

Community
  • 1
  • 1
three_pineapples
  • 11,579
  • 5
  • 38
  • 75
  • Thanks a lot. It is working. Can you explain me how it is working. I think it is somehow giving the absolute path to the file dynamically. And what is that _ __file__ _ parameter? I never saw that kind of parameter. Kind of enum? – srinath29 Jan 22 '16 at 02:50
  • Hi @srinath29 I've updated my answer with an explanation of how it works. – three_pineapples Jan 22 '16 at 03:53
  • Thanks a lot @three_pineapples . . I understood. – srinath29 Jan 24 '16 at 08:17