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/

I receive the error:

Traceback (most recent call last):
  File "", line 2, in <module>
OSError: [Errno 2] No such file or directory: ''

How should I read this error and what to do ?

This question is tagged with python python-2.7 python-module

~ Asked on 2013-03-31 01:04:57

The Best Answer is


Have you noticed that you don't get the error if you run

python ./

instead of


This is because sys.argv[0] will read ./ in the former case, which gives os.path.dirname something to work with. When you don't specify a path, sys.argv[0] reads simply, and os.path.dirname cannot determine a path.

~ Answered on 2013-03-31 01:19:02


I had this error because I was providing a string of arguments to 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)

~ Answered on 2015-04-21 14:26:58

Most Viewed Questions: