I have the following file structure:
test/
test1.py
test2.py
text.txt
Here are the contents of the files
test1.py:
import sys
sys.path.append('../')
import test2
test2.read()
test2.py:
def read():
with open('text.txt', 'rb') as f:
print f.read()
if __name__ == "__main__":
read()
text.txt
contains a line of text. When I run test1.py
, I get a "File not found" error:
Traceback (most recent call last):
File "test1.py", line 5, in <module>
test2.read()
File "../test2.py", line 2, in read
with open('text.txt', 'rb') as f:
IOError: [Errno 2] No such file or directory: 'text.txt'
I kind of understand why this error is coming up. But how do I deal with these kind of errors. I would like the code in test2.py
to be like library code which I can use anywhere.