When you call class1.py
from main.py
, your working directory is lib/
(or wherever you called main.py
from) and not module1
.
This means that if you want to access foo.txt
you need to specify the path from the working directory, not from where the class1.py
is located.
Example:
Assuming that you run main.py
from directory lib/
:
# class1.py
class Foo():
def read1(self):
try:
f = open('foo.txt')
print("Successfully opened 'foo.txt'.")
print(f.read())
except OSError:
print("Error when trying to read 'foo.txt'.")
def read2(self):
try:
f = open('module1/foo.txt')
print("Successfully opened 'module1/foo.txt'.")
print(f.read())
except OSError:
print("Error when trying to read 'module1/foo.txt'.")
if __name__ == '__main__':
foo = Foo()
foo.read1()
foo.read2()
# __init__.py
from module1.class1 import Foo
# main.py
from module1 import Foo
foo = Foo()
foo.read1()
foo.read2()
- If you are inside
module1
and run class1.py
:
Successfully opened 'foo.txt'.
...file contents...
Error when trying to read 'module1/foo.txt'.
As you can see read1
worked and not read2
.
- If you are in
lib/
and call main.py
, you'll get:
Error when trying to read 'foo.txt'.
Successfully opened 'module1/foo.txt'.
...file contents...
This time read2()
worked and not read1()
.
Notes:
- if you call
class1.py
directly from lib/module1
then read_file_1()
will work instead of read_file_2()
.
- you can alleviate this issue completely by using absolute paths*