-3

I'm trying to import 'file.py' in another file (lets call it 'current.py') in Python3. Both the files are in same directory.

I tried all solutions listed in this link :Importing files from different folder in Python but am still unable to resolve the issue.

Also can someone please tell me what to do when the file I'm working on is in different directory from the one I want to use

0AJ0
  • 88
  • 1
  • 3
  • 10

2 Answers2

0

If you have:

.
|_ file.py
|_ current.py

And you want to import the object Foo in current.py, just write at the beginning of current.py

import file
from file import Foo

UPDATE 1: Here is an example

Well, you missed something then, I did this and it worked perfectly:

➜  tree
.
├── current.py
├── file.py
2 files
➜  python3 current.py
hello

here is current.py:

import file
from file import Object
a = Object()

and file.py:

class Object:
    def __init__(self):
        print('hello')
pBouillon
  • 268
  • 4
  • 14
  • I'm using Rodeo on Mac where it's not working. When I use PyCharm its working successfully. Can you please help me with this? – 0AJ0 Jun 02 '17 at 05:20
0

Assuming the file you like to import is called my_file.py just use:

import my_file as mf

If no error raises, the problem may be related to your code inside of a

if __name__ == '__main__':

statement. If you are using this statement in your my_file.py this part won't be imported because you're not running your file from there. Only function, classes and other structures outside of this if statement will be imported.

Franz
  • 623
  • 8
  • 14