判斷目錄是否存在
import os
dirs = 'C:\Users\Administrator\Desktop\work\python\'
if not os.path.exists(dirs):
os.makedirs(dirs)
判斷文件夾是否存在
import os
path =os.path.dirname(os.getcwd())+ '\\Screenshots\\'
if not os.path.exists(path):
os.makedirs(path)
判斷文件是否存在
import os
filename ='C:\Users\Administrator\Desktop\work\python\poem.txt'
if not os.path.exists(filename):
os.system(r"touch {}".format(path)) #調用系統命令行來創建文件
os.getcwd() :獲取的當前最外層調用的腳本路徑,即getPath所在的目錄也可描述為起始的執行目錄,A調用B,起始的是A,那么獲取的就是A所在的目錄路徑。 獲取腳本路徑所在的上層目錄
os.path.dirname():去掉腳本的文件名,返回目錄。返回腳本文件所在的目錄路徑