python 判斷目錄和文件、文件夾 是否存在,若不存在即創建


判斷目錄是否存在
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():去掉腳本的文件名,返回目錄。返回腳本文件所在的目錄路徑


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM