python判斷檔案資料夾是否存在並建立

2021-09-27 07:26:47 字數 562 閱讀 1151

方式還是有挺多的,這裡採取最為簡單的os包

import os

import codecs

# 判斷資料夾是否存在,不存在則建立

dirs1 = 'd:\\history'

if not os.path.exists(dirs1):

os.makedirs(dirs1)

# 判斷檔案是否存在,不存在則建立

file1 = 'd:\\conf.ini'

if not os.path.exists(file1):

# w是覆蓋,a是追加,a+,w+是如不存在就建立

with codecs.open(file1,'a+',encoding='utf-8') as f:

f.write("")

'''這裡多說一句

使用codecs的with open的好處是,平常的open需要開啟之後需要close

因為open之後是放在記憶體裡寫的,關閉之後資料才會寫到硬碟裡,否則會造成部分資料丟失

而with則不需要

'''

python判斷檔案或資料夾是否存在

主要涉及的模組是python的os模組 import osos.path.exists 檔名或者資料夾名 判斷是否存在檔案或者資料夾 返回true or false os.path.isfile 檔名或者資料夾名 判斷是否是檔案 返回true or false os.makedirs 資料夾或者路徑...

判斷資料夾是否存在

access函式判斷資料夾或者檔案是否存在 函式原型 int access const char filename,int mode 所屬標頭檔案 io.h filename 可以填寫資料夾路徑或者檔案路徑 mode 0 f ok 只判斷是否存在 2 r ok 判斷寫入許可權 4 w ok 判斷讀取...

C C 判斷檔案 資料夾是否存在

一 判斷資料夾是否存在 1.用createdirectory filemanege null 如果資料夾filemanege不存在,則建立。2.或者if access filemanege 0 1 表示filemanege不存在。3.或者bool pathisdirectory lpctstr ps...