背景
python的os模塊是可以動態創建目錄的,但是很多人只瞭解單級目錄的創建方法,其實os模塊封裝了完整的目錄創建相關的方法。
創建單級目錄
os.mkdir('./path')
創建多級目錄
os.makedirs('./path/path2/path3')
其他
另外os也有很多實用的功能,這裏再介紹下路徑相關的方法。
file_path = '/Users/music/Desktop/test.txt'
# 1、分割 路徑 文件名
# 返回值爲元組 ('/Users/music/Desktop', 'test.txt')
path, name = os.path.split(file_path)
# 2、分割 文件 拓展名
# 返回值爲元組 ('/Users/music/Desktop/test', '.txt')
file, extension = os.path.splitext(file_path)
# 3、獲取當前相對路徑的絕對路徑
# 假設當前路徑爲 /Users/music/Desktop
# 返回值爲字符串 '/Users/music/Desktop/test.txt'
file_path_1 = './test.txt'
file_path_abs = os.path.abspath(file_path_1)
# 判斷是否爲路徑且存在
os.path.isdir()
# 判斷是否爲文件且存在
os.path.isfile()
# 判斷是否存在 路徑-文件
os.path.exists()
os.path.isabs()
# 多路徑拼接
os.path.join()