The python interpreter is an example of an error executing in a different directory than the script is in:
(tensorflow) [root@localhost python]# cat test.txt
a
b
c
py file in the same directory:
(tensorflow) [root@localhost python]# cat sto.py
with open('test.txt', 'r') as f:
for line in f:
print(line)
Return to the parent directory:
cd..
Run the sto.py file:
(tensorflow) [root@localhost vagrant]# python ./python/sto.py
Traceback (most recent call last):
File "./python/sto.py", line 1, in <module>
with open('test.txt', 'r') as f:
IOError: [Errno 2] No such file or directory: 'test.txt'
Solution: Use os to add the current directory to the system path:
(tensorflow) [root@localhost python]# vim sto.py
import os
MYDIR = os.path.dirname(__file__)
with open(os.path.join(MYDIR, 'test.txt')) as f:
for line in f:
print(line)
Run again:
(tensorflow) [root@localhost vagrant]# python ./python/sto.py
a
b
c
Reference: [ https://stackoverflow.com/questions/27975415/python-ioerror-errno-2-no-such-file-or-directory-ulastid-py-for-file-in]