如何使用 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP