-1

I have the following files:

t.py:  
def foo(): 
    print("foo")

folder/t.py: 
def foo(): 
    print("bar")

folder/main.py: 

import t
if __name__ == "__main__":
  t.foo()

when I run it on the command line with python -m folder.main it prints "foo" but I actually want to import folder/t.py so that it prints "bar" instead. How can I do that?

ksohan
  • 1,165
  • 2
  • 9
  • 23
JRR
  • 6,014
  • 6
  • 39
  • 59
  • 1
    `import folder.t` https://stackoverflow.com/questions/1260792/import-a-file-from-a-subdirectory –  Feb 15 '22 at 18:39
  • what folder are you running from? I think that might make the difference here. – Willow Feb 15 '22 at 18:41

2 Answers2

0

You can import as, so like import folder.t as ft then run ft.foo()

anarchy
  • 3,709
  • 2
  • 16
  • 48
0

Use the following code in main.py and run the command python -m folder.main.

sys.path.append() will add the folder to the system path so that it can find the module t in that folder.

import sys
sys.path.append('.\\folder\\')

from folder import t
if __name__ == "__main__":
  t.foo()

ksohan
  • 1,165
  • 2
  • 9
  • 23