日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

python?判斷文件或文件夾是否存在_python

作者:夏華東的博客 ? 更新時(shí)間: 2022-05-21 編程語言

Python 操作文件時(shí),我們一般要先判斷指定的文件或目錄是否存在,不然容易產(chǎn)生異常。

1.文件

# 是否存在
import os
os.path.exists(test_file.txt)
# 是不是文件
import os
os.path.isfile("test-data")
# 是不是文件
from pathlib import Path
my_file = Path("/path/to/file")
my_file.is_file()

2.文件夾

# 是否存在
import os
os.path.exists(test_dir)
# 是不是文件夾
from pathlib import Path
my_file = Path("/path/to/file")
my_file.is_dir()
# 是否存在
from pathlib import Path
my_file = Path("/path/to/file")
my_file.exists()

3.補(bǔ)充

例如我們可以使用 os 模塊的 os.path.exists() 方法來檢測文件是否存在:

import os.path
os.path.isfile(fname)

如果你要確定他是文件還是目錄,從 Python 3.4 開始可以使用 pathlib 模塊提供的面向?qū)ο蟮姆椒?(Python 2.7 為 pathlib2 模塊):

from pathlib import Path

my_file = Path("/path/to/file")
if my_file.is_file():
? ? # 指定的文件存在

檢測是否為一個(gè)目錄:

if my_file.is_dir():
? ? # 指定的目錄存在

如果要檢測路徑是一個(gè)文件或目錄可以使用 exists() 方法:

if my_file.exists():
? ? # 指定的文件或目錄存在

在 try 語句塊中你可以使用 resolve() 方法來判斷:

try:
? ? my_abs_path = my_file.resolve()
except FileNotFoundError:
? ? # 不存在
else:
? ? # 存在

原文鏈接:https://blog.csdn.net/weixin_44493841/article/details/123553838

欄目分類
最近更新