search

Home  >  Q&A  >  body text

python - os.mkdir() 和 os.makedirs() 的区别

用Python做的 爬虫:

为什么第一个没有报错?

thx in advance

PHPzPHPz2890 days ago618

reply all(1)I'll reply

  • PHPz

    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.

    reply
    0
  • Cancelreply