1. 程式人生 > 實用技巧 >如何使用python 新建資料夾以及遞迴建立資料夾

如何使用python 新建資料夾以及遞迴建立資料夾

轉載:如何使用python 新建資料夾以及遞迴建立資料夾 | 酷python (coolpython.net)

1. os.mkdir

使用python建立資料夾,通常使用os.mkdir方法,在使用這個方法時有幾個小的細節需要注意,假設你的程式碼是這樣編寫的

import os

os.mkdir('/dir_1/dir_2/dir_3')

你需要保證/dir_1/dir_2 是存在的,否則將引發FileNotFoundError,如果/dir_1/dir_2/dir_3 已經存在,又會引發FileExistsError,通常,我會使用os.path.exists方法判斷關鍵的目錄是否已經存在,來決定是否新建資料夾。

2. os.makedirs

os.makedirs 可以視為os.mkdir的升級版本,它以遞迴的方式建立資料夾,如果dir_1不存在,就先建立dir_1,而後遞迴建立剩餘的資料夾,這樣就不存在FileNotFoundError;如果想要建立的目錄已經存在,也沒有關係,設定exist_ok = True, 就不會引發FileExistsError

import os

os.makedirs('./1/2/3/4/5', exist_ok=True)

這兩行程式碼你可以執行多次,不會有任何錯誤或異常