共計 375 個字符,預計需要花費 1 分鐘才能閱讀完成。
在 Python 中,可以使用以下幾種方法來判斷文件是否存在:
- 使用
os.path
模塊的exists()
函數:
import os
if os.path.exists(" 文件路徑 "):
print(" 文件存在 ")
else:
print(" 文件不存在 ")
- 使用
os.path
模塊的isfile()
函數,判斷是否是一個文件:
import os
if os.path.isfile(" 文件路徑 "):
print(" 文件存在 ")
else:
print(" 文件不存在 ")
- 使用
Path
對象的exists()
方法:
from pathlib import Path
file = Path(" 文件路徑 ")
if file.exists():
print(" 文件存在 ")
else:
print(" 文件不存在 ")
這些方法都可以用來判斷文件是否存在,具體使用哪種方法取決于個人喜好和需求。
丸趣 TV 網 – 提供最優質的資源集合!
正文完