Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 ?

like image 282
Hugolpz Avatar asked Mar 31 '13 01:03

Hugolpz


People also ask

How do I fix Errno 2 No such file or directory in Python?

The Python "FileNotFoundError: [Errno 2] No such file or directory" occurs when we try to open a file that doesn't exist in the specified location. To solve the error, move the file to the directory where the Python script is located if using a local path, or use an absolute path.

How do I fix error No such file or directory?

In some cases, this error could be shown when the path of the specified file or folders exceeds 258 characters in length. The way to solve this is to reduce the length of the full path to the items specified, either by moving or renaming the file(s) and/or containing folders.

How do I fix Python FileNotFoundError?

The Python FileNotFoundError: [Errno 2] No such file or directory error is often raised by the os library. This error tells you that you are trying to access a file or folder that does not exist. To fix this error, check that you are referring to the right file or folder in your program.

What is errno2?

The error "FileNotFoundError: [Errno 2] No such file or directory" is telling you that there is no file of that name in the working directory. So, try using the exact, or absolute path. In the above code, all of the information needed to locate the file is contained in the path string - absolute path.


1 Answers

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

python ./script.py 

instead of

python script.py 

This is because sys.argv[0] will read ./script.py 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 script.py, and os.path.dirname cannot determine a path.

like image 182
zigg Avatar answered Oct 28 '22 07:10

zigg