如何使用Python建立不存在的目錄?
Python 內建了檔案建立、寫入和讀取功能。在Python中,可以處理兩種型別的檔案:文字檔案和二進位制檔案(以二進位制語言,0和1編寫)。您可以建立檔案,也可以在不再需要時刪除它們。
以程式設計方式建立目錄很簡單,但是您必須確保它們不存在。如果您不這樣做,將會遇到麻煩。
示例1
在Python中,使用os.path.exists() 方法 檢查目錄 是否已存在,然後使用os.makedirs() 方法 建立它。
內建的Python方法os.path.exists()用於確定提供的路徑是否存在。os.path.exists()方法會生成一個布林值,該值根據路徑是否存在而為True或False。
Python的OS模組 包含用於建立和刪除目錄(資料夾)、檢索其內容、更改和識別當前目錄以及更多功能的函式。要與底層作業系統互動,您必須首先匯入os模組。
#python program to check if a directory exists import os path = "directory" # Check whether the specified path exists or not isExist = os.path.exists(path) #printing if the path exists or not print(isExist)
輸出
執行上述程式後,將生成以下輸出。
True Let’s look at a scenario where the directory doesn’t exist.
示例2
內建的Python方法os.makedirs()用於遞迴地構建目錄。
#python program to check if a directory exists import os path = "pythonprog" # Check whether the specified path exists or not isExist = os.path.exists(path) if not isExist: # Create a new directory because it does not exist os.makedirs(path) print("The new directory is created!")
輸出
執行上述程式後,將生成以下輸出。
The new directory is created!
示例3
要建立目錄,首先使用os.path.exists(directory)檢查它是否已經存在。然後您可以使用以下方法建立它:
#python program to check if a path exists #if it doesn’t exist we create one import os if not os.path.exists('my_folder'): os.makedirs('my_folder')
示例4
pathlib模組包含表示檔案系統路徑併為各種作業系統提供語義的類。純路徑提供純粹的計算操作而無需I/O,具體路徑繼承自純路徑,但還提供I/O操作,這兩種是路徑類的兩種型別。
# python program to check if a path exists #if path doesn’t exist we create a new path from pathlib import Path #creating a new directory called pythondirectory Path("/my/pythondirectory").mkdir(parents=True, exist_ok=True)
示例5
# python program to check if a path exists #if path doesn’t exist we create a new path import os try: os.makedirs("pythondirectory") except FileExistsError: # directory already exists pass
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP