How to import python file located in same subdirectory in a pycharm project

Chris picture Chris · Mar 11, 2016 · Viewed 88.4k times · Source

I have an input error in pycharm when debugging and running.

My project structure is rooted properly, etc./HW3/. so that HW3 is the root directory.

I have a subfolder in HW3, util, and a file, util/util.py. I have another file in util called run_tests.py.

In run_tests.py, I have the following import structure,

from util.util import my_functions, etc.

This yields an input error, from util.util import load_dataset,proportionate_sample ImportError: No module named 'util.util'; 'util' is not a package


However, in the exact same project, in another directory (same level as util) called data, I have a file data/data_prep.py, which also imports functions from util/util.py using a similar import statement...and it runs without any problems.


Obviously, I am doing this in the course of doing a homework, so please understand: this is ancillary to the scope of the homework.


The problem goes away when I move the file to another directory. So I guess this question is How do I import a python file located in the same directory in a pycharm project? Because pycharm raises an error if I just do import util and prompts me to use the full name from the root.

Answer

imanzabet picture imanzabet · Jul 30, 2017

Recommended Way:

Make sure to set the working folder as Sources.

You can do it in Pycharm -> Preferences -> Project: XYZ -> Project Structure

Select your working folder and mark it as Sources. Then Pycharm recognize the working folder as a Source folder for the project and you will be able to simply add other files within that folder by using

import filename.py

or

from filename.py import mudule1

=================

Not recommended way:

In Pycharmyou can simply add . before the .py file which you are going to import it from the same folder. In your case it will be

from .util import my_functions

Resource

There is a good reference also for more information with example how to implement Package Relative Imports. I would highly recommend to check this page.

Package Relative Imports