当前位置: > 开发教程 > ajax教程 >

python判断文件或文件夹是否存在

时间:2022-03-19 13:14 来源:未知 作者:初相遇 收藏

这篇文章主要介绍了python判断文件或文件夹是否存在,Python操作文件时,我们一般要先判断指定的文件或目录是否存在,不然容易产生异常,下面我们就来学习如何利用python检查文件是否存在吧

Python 操作文件时,我们一般要先判断指定的文件或目录是否存在,不然容易产生异常。

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.补充

例如我们可以使用 os 模块的 os.path.exists() 方法来检测文件是否存在:

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

如果你要确定他是文件还是目录,从 Python 3.4 开始可以使用 pathlib 模块提供的面向对象的方法 (Python 2.7 为 pathlib2 模块):

from pathlib import Path

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

检测是否为一个目录:

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

如果要检测路径是一个文件或目录可以使用 exists() 方法:

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

在 try 语句块中你可以使用 resolve() 方法来判断:

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

到此这篇关于python 判断文件或文件夹是否存在的文章就介绍到这了,更多相关python 检测文件是否存在内容请搜索源码搜藏网以前的文章或继续浏览下面的相关文章希望大家以后多多支持源码搜藏网!


ajax教程阅读排行

最新文章