Python:OSError:[Errno 2] 没有那个文件或目录:'' [英] Python: OSError: [Errno 2] No such file or directory: ''

查看:98
本文介绍了Python:OSError:[Errno 2] 没有那个文件或目录:''的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 100 行、3 年的 Python 爬虫程序,但现在是错误的.起跑线是:

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!)

运行时,

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

我收到错误:

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: ''

我应该如何阅读此错误以及该怎么做?

推荐答案

你有没有注意到运行时没有报错

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

python ./script.py

代替

python script.py

这是因为 sys.argv[0] 在前一种情况下会读取 ./script.py,这给出了 os.path.dirname 可以使用的东西.不指定路径时,sys.argv[0] 只读取script.pyos.path.dirname 无法确定一条路径.

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.

这篇关于Python:OSError:[Errno 2] 没有那个文件或目录:''的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆