Reputation: 159
I'm running this code:
import os
file_path = os.path.dirname(__file__)
print file_path
accel = open(os.path.dirname(__file__) + '/../imu/accel.txt')
First I ran it from my atom editor using the 'script' package and it outputted:
But when I ran the same code from the terminal I get:
Traceback (most recent call last):
File "imu_pub2.py", line 9, in <module>
accel = open(os.path.dirname(__file__) + '/../imu/accel.txt')
IOError: [Errno 2] No such file or directory: '/../imu/accel.txt'
Why is this happening?
The compile error happens at the last line of the code. For some reason in the terminal the print statement is not printing anything. The problem starts there.
Upvotes: 1
Views: 473
Reputation: 5828
Change os.path.dirname(__file__)
to os.path.dirname(os.path.abspath(__file__))
The problem is that when you run your script as python imu_pub2.py
the __file__
variable is set to "imu_pub2.py". That string is just a filename with no directory part, so dirname(__file__)
produces an empty string. That means that file_path
is an empty string, which is why nothing shows up when you print
it. Since the result of dirname
is empty, accel
gets set to just "/../imu/accel.txt" and apparently no such file exists on your machine so the open
fails.
Using abspath
will get the full directory path for __file__
, and that will let dirname
produce the result you want.
BTW, kra3 is correct when he says to use os.path.join
instead of just concatenating strings together. But that's not the cause of the bug.
Upvotes: 1