0

I've got this structure:

│
├ main.py
├ dir
|  ├─ data.txt
|  └─ other.py

Contents from other.py:

print(open('data.txt', 'utf-8').read())

I run main.py. It must start dir/other.py.
But other.py for works needs data.txt. Is there a way to start other.py from main.py, not editing other.py?

Note
User must be able to start other.py manualy without any errors

2
  • Is other.py to be imported as a module or run as a separate process? Commented Jun 29, 2019 at 8:55
  • It's not important. Commented Jun 29, 2019 at 10:35

2 Answers 2

1

For this purpose you can use the import keyword. All you have to do is create an __init__.py script under the dir directory which will define the directory as a library. Then you can just use import others in the main script.

It is recommended to modify the others.py script with the below snippet

if __name__ == '__main__':
    // do stuff

otherwise it will execute the library each time you import it

update

It is far more simple. You just have to change directory with the os.chdir("./dir") call. After that you can run a simple import and the script will be executed.

./dir/other.py:
print("Module starts")
print(open('data', 'r').read())
print("Module ends")

./main.py
print("Main start")
import os
os.chdir("./dir")
from others import other
print("Main end" )

Sign up to request clarification or add additional context in comments.

Comments

0

You can import other in main file like from dir.other import *

3 Comments

Egh... I would have an error No such file or directory: 'data.txt'
To use data.txt which exists in dir from main.py you should use 'dir/data.txt' as it is in dir directory not in same directory as main.py
I thought this at first. But the user sometimes could start other.py manually.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.