判斷目錄是否存在
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))? #調(diào)用系統(tǒng)命令行來創(chuàng)建文件
os.getcwd() :獲取的當(dāng)前最外層調(diào)用的腳本路徑渐排,即getPath所在的目錄也可描述為起始的執(zhí)行目錄,A調(diào)用B灸蟆,起始的是A驯耻,那么獲取的就是A所在的目錄路徑。 獲取腳本路徑所在的上層目錄
os.path.dirname():去掉腳本的文件名炒考,返回目錄可缚。返回腳本文件所在的目錄路徑