I suspect this is a very newbie question but I can\'t find any solutions that are helping :( I\'ve been trying to get started with Python by building a simple Twitter bot w
Probably the python interpreter is being executed from a different directory than where your script lives.
Here's the same setup:
oliver@aldebaran /tmp/junk $ cat test.txt
a
b
c
baseoliver@aldebaran /tmp/junk $ cat sto.py
with open('test.txt', 'r') as f:
for line in f:
print(line)
baseoliver@aldebaran /tmp/junk $ python sto.py
a
b
c
baseoliver@aldebaran /tmp/junk $ cd ..
baseoliver@aldebaran /tmp $ python ./junk/sto.py
Traceback (most recent call last):
File "./junk/sto.py", line 1, in
with open('test.txt', 'r') as f:
IOError: [Errno 2] No such file or directory: 'test.txt'
To solve this, import os and use absolute pathnames:
import os
MYDIR = os.path.dirname(__file__)
with open(os.path.join(MYDIR, 'test.txt')) as f:
pass
# and so on