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

Viewed 121044

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.

8 Answers

Right-click on the folder which you want to be marked as the source > Mark Directory as > Source root.

In my case, it worked only when I omit the extension. Example:

import filename

I had the same issue with pycharm, but the actual mistake was that the file I was trying to import didn't have a .py extension, even though I was able to run it as a standalone script. Look in the explorer window and make sure it has a .py extension. If not, right click on the file in the explorer window, pick refactor, and then rename it with a .py extension.

In Pycharm go to "Run - Configuration" and uncheck 'Add Content root to Pythonpath' and 'Add source roots to Pythonpath', then use

from filename import functionname

For me the issue was, the source directory was marked correctly, but my file to import was named starting with numeric value. Resolved by renaming it.

import 01_MyModuleToImport

to

import MyModuleToImport
Related