參考博客:python創建文件和文件夾_ -CSDN博客_python 創建文件
創建文件夾
import os def mkdir(path): folder = os.path.exists(path) if not folder: #判斷是否存在文件夾如果不存在則創建為文件夾 os.makedirs(path) #makedirs 創建文件時如果路徑不存在會創建這個路徑 print "--- new folder... ---" print "--- OK ---" else: print "--- There is this folder! ---" file = "G:\\xxoo\\test" mkdir(file) #調用函數
os.getcwd()可以查看py文件所在路徑;
在os.getcwd()后邊 加上 [:-4] + 'xxoo\\' 就可以在py文件所在路徑下創建 xxoo文件夾
import os folder = os.getcwd()[:-4] + 'new_folder\\test\\' #獲取此py文件路徑,在此路徑選創建在new_folder文件夾中的test文件夾 if not os.path.exists(folder): os.makedirs(folder)
在py文件路徑下創建test的txt文件
import os def txt(name,text): #定義函數名 b = os.getcwd()[:-4] + 'new\\' # 實際使用中我把[:-4]刪掉才得到正確的路徑,這里對轉載的博客存疑 if not os.path.exists(b): #判斷當前路徑是否存在,沒有則創建new文件夾 os.makedirs(b) xxoo = b + name + '.txt' #在當前py文件所在路徑下的new文件中創建txt file = open(xxoo,'w') file.write(text) #寫入內容信息 file.close() print ('ok') txt('test','hello,python') #創建名稱為test的txt文件,內容為hello,python
python判斷文件是否存在的三種方式:Python判斷文件是否存在的三種方法 - j_hao104 - 博客園 (cnblogs.com)
1.使用os模塊
os模塊中的os.path.exists()
方法用於檢驗文件是否存在。
- 判斷文件是否存在
import os os.path.exists(test_file.txt) #True os.path.exists(no_exist_file.txt) #False
- 判斷文件夾是否存在
import os os.path.exists(test_dir) #True os.path.exists(no_exist_dir) #False
可以看出用os.path.exists()
方法,判斷文件和文件夾是一樣。
其實這種方法還是有個問題,假設你想檢查文件“test_data”是否存在,但是當前路徑下有個叫“test_data”的文件夾,這樣就可能出現誤判。為了避免這樣的情況,可以這樣:
- 只檢查文件
import os os.path.isfile("test-data")
通過這個方法,如果文件”test-data”不存在將返回False,反之返回True。
即是文件存在,你可能還需要判斷文件是否可進行讀寫操作。
判斷文件是否可做讀寫操作
使用os.access()
方法判斷文件是否可進行讀寫操作。
語法:
os.access(path, mode)
path為文件路徑,mode為操作模式,有這么幾種:
-
os.F_OK: 檢查文件是否存在;
-
os.R_OK: 檢查文件是否可讀;
-
os.W_OK: 檢查文件是否可以寫入;
-
os.X_OK: 檢查文件是否可以執行
該方法通過判斷文件路徑是否存在和各種訪問模式的權限返回True或者False。
import os if os.access("/file/path/foo.txt", os.F_OK): print "Given file path is exist." if os.access("/file/path/foo.txt", os.R_OK): print "File is accessible to read" if os.access("/file/path/foo.txt", os.W_OK): print "File is accessible to write" if os.access("/file/path/foo.txt", os.X_OK): print "File is accessible to execute"
2.使用Try語句
可以在程序中直接使用open()
方法來檢查文件是否存在和可讀寫。
語法:
open()
如果你open的文件不存在,程序會拋出錯誤,使用try語句來捕獲這個錯誤。
程序無法訪問文件,可能有很多原因:
-
如果你open的文件不存在,將拋出一個
FileNotFoundError
的異常; -
文件存在,但是沒有權限訪問,會拋出一個
PersmissionError
的異常。
所以可以使用下面的代碼來判斷文件是否存在:
try: f =open() f.close() except FileNotFoundError: print "File is not found." except PermissionError: print "You don't have permission to access this file."
其實沒有必要去這么細致的處理每個異常,上面的這兩個異常都是IOError
的子類。所以可以將程序簡化一下:
try: f =open() f.close() except IOError: print "File is not accessible."
使用try語句進行判斷,處理所有異常非常簡單和優雅的。而且相比其他不需要引入其他外部模塊。
創建文件: