[python] Python: OSError: [Errno 2] No such file or directory: ''

I have a 100 lines, 3 years old python scraper that now bug. Starting lines are:

import urllib, re, os, sys, time    # line 1: import modules
os.chdir(os.path.dirname(sys.argv[0])) # line 2: all works in script's folder > relative address
# (rest of my script here!)

When run,

$cd /my/folder/
$python script.py

I receive the error:

python script.py 
Traceback (most recent call last):
  File "script.py", line 2, in <module>
    os.chdir(os.path.dirname(sys.argv[0]))
OSError: [Errno 2] No such file or directory: ''

How should I read this error and what to do ?

This question is related to python python-2.7 python-module

The answer is


I had this error because I was providing a string of arguments to subprocess.call instead of an array of arguments. To prevent this, use shlex.split:

import shlex, subprocess
command_line = "ls -a"
args = shlex.split(command_line)
p = subprocess.Popen(args)

Use os.path.abspath():

os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))

sys.argv[0] in your case is just a script name, no directory, so os.path.dirname() returns an empty string.

os.path.abspath() turns that into a proper absolute path with directory name.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to python-2.7

Numpy, multiply array with scalar Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION] How to create a new text file using Python Could not find a version that satisfies the requirement tensorflow Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support Display/Print one column from a DataFrame of Series in Pandas How to calculate 1st and 3rd quartiles? How can I read pdf in python? How to completely uninstall python 2.7.13 on Ubuntu 16.04 Check key exist in python dict

Examples related to python-module

ImportError: libSM.so.6: cannot open shared object file: No such file or directory How to write a Python module/package? Python: OSError: [Errno 2] No such file or directory: '' Unable to import a module that is definitely installed Installing python module within code How to import other Python files? How do I find out my python path using python? What does if __name__ == "__main__": do? How to do relative imports in Python? How to import a module given the full path?