语言: Python2.7
IDE: Pycharm
os: Linux
用Python做的 爬虫:
第一个建立在 project
folder 下用 os.mkdir('home/img/')
创建文件夹存储数据,文件夹正常建立
第二个加入RedisQueue
,爬虫程序放在 /usr/lib/python2.7
, rq 主体放在 project
folder下面, 在爬虫程序里面用 os.mkdir('home/img/')
报错,用 os.makedirs('home/img/')
正常建立。
为什么第一个没有报错?
thx in advance
PHPz2017-04-17 17:57:52
The difference between
os.mkdir and os.makedirs is os.makedirs
會遞迴地去建立目錄,也就是說連同中繼的目錄也會一起建立,就類似於 Linux 中的 mkdir -p
.
>>> import os
>>> os.mkdir('foo/bar')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory: 'foo/bar'
>>> os.makedirs('foo/bar')
Use os.mkdir
時,如果你給定的 path 參數是個多層的 path,如果某個中繼的目錄不存在(比如說上例中的 foo
), Python will report an error.
But if you use os.makedirs
則 Python 會連同中間的目錄一起建立.但有一點值得注意,當 path 末端的目錄已經存在的話,os.makedirs
, it will also cause an exception.
I think your problem is here, you can check home
whether the directory exists at the beginning.
It should be noted that the path identification here depends on where you start the Python interpreter, which means you need to make sure that there must be python
所在的目錄下面要有 home
才能避免 os.mkdir
under the directory where you run python
to avoid os.mkdir
error.