1. 程式人生 > >【Python】 建立目錄資料夾

【Python】 建立目錄資料夾

【Python】 建立目錄資料夾

轉自:https://www.cnblogs.com/monsteryang/p/6574550.html

Python對檔案的操作還算是方便的,只需要包含os模組進來,使用相關函式即可實現目錄的建立。

主要涉及到三個函式

1、os.path.exists(path) 判斷一個目錄是否存在

2、os.makedirs(path) 多層建立目錄

3、os.mkdir(path) 建立目錄

DEMO

直接上程式碼

def mkdir(path):
    # 引入模組
    import os
 
    # 去除首位空格
    path=path.strip()
    # 去除尾部 \ 符號
    path=path.rstrip("\\")
 
    # 判斷路徑是否存在
    # 存在     True
    # 不存在   False
    isExists=os.path.exists(path)
 
    # 判斷結果
    if not isExists:
        # 如果不存在則建立目錄
         # 建立目錄操作函式
        os.makedirs(path) 
 
        print path+' 建立成功'
        return True
    else:
        # 如果目錄存在則不建立,並提示目錄已存在
        print path+' 目錄已存在'
        return False
 
# 定義要建立的目錄
mkpath="d:\\qttc\\web\\"
# 呼叫函式
mkdir(mkpath)

以上是我寫好的一個函式,只需要傳入你要建立目錄的全路徑即可。

說明

在以上DEMO的函式裡,我並沒有使用os.mkdir(path)函式,而是使用了多層建立目錄函式os.makedirs(path)。這兩個函式之間最大的區別是當父目錄不存在的時候os.mkdir(path)不會建立,os.makedirs(path)則會建立父目錄

比如:例子中我要建立的目錄web位於D盤的qttc目錄下,然而我D盤下沒有qttc父目錄,如果使用os.mkdir(path)函式就會提示我目標路徑不存在,但使用os.makedirs(path)會自動幫我建立父目錄qttc,請在qttc目錄下建立子目錄web。