前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python: 判断文件/目录是否存在

Python: 判断文件/目录是否存在

作者头像
Exploring
发布2022-09-20 14:05:21
6.1K0
发布2022-09-20 14:05:21
举报
文章被收录于专栏:数据处理与编程实践

文章背景: 在读写文件之前,需要判断文件或目录是否存在,不然某些处理方法可能会使程序出错。所以最好在做任何操作之前,先判断文件/目录是否存在。下面介绍两种方法。

1 使用os模块

2 使用pathlib模块

1 使用os模块

os模块中的os.path.exists(path)方法用于检验文件/目录是否存在。

Return True if path refers to an existing path or an open file descriptor. Returns False for broken symbolic links.

代码语言:javascript
复制
import os

file_path = r"C:\test\test.txt"
print(os.path.exists(file_path))

folder_path = r"C:\test"
print(os.path.exists(folder_path))

上述代码块中,判断文件/目录是否存在,用的是同一个方法,os.path.exists(path)。对于不带后缀名的文件,在进行判断时,容易与文件夹相混淆,从而造成误判。

为了避免文件被误判,针对文件,可以使用os.path.isfile(path)方法。

Return True if path is an existing regular file.

代码语言:javascript
复制
import os

file_path = r"C:\test\new.txt"
print(os.path.isfile(file_path))

此外,针对文件夹,还可以使用os.path.isdir(path)方法。

Return True if path is an existing directory.

代码语言:javascript
复制
import os

folder_path = r"C:\test"
print(os.path.isdir(folder_path))

综上,通过os模块,可以采用如下方法判断文件/目录是否存在。

  • os.path.exists(path) 判断文件/目录的路径是否存在
  • os.path.isfile(path) 判断文件是否存在
  • os.path.isdir(path) 判断文件夹是否存在
2 使用pathlib模块

使用pathlib模块,需要先使用文件路径来创建path对象。此路径可以是文件名或目录路径。

代码语言:javascript
复制
from pathlib import Path

file_path = r"C:\test\new.txt"
my_file = Path(file_path)
print(my_file.exists())

folder_path = r"C:\test"
my_folder = Path(folder_path)
print(my_folder.exists())

上述代码块中,判断文件/目录是否存在,用的是同一个方法exists() 。如果文件/目录存在,则返回True;否则,返回False

此外,针对文件,还可以使用is_file()方法;针对目录,还可以使用is_dir()方法。文件(或目录)若存在,则返回True;否则,返回False

代码语言:javascript
复制
from pathlib import Path

file_path = r"C:\test\new.txt"
my_file = Path(file_path)
print(my_file.is_file())

folder_path = r"C:\test"
my_folder = Path(folder_path)
print(my_folder.is_dir())

综上,通过pathlib模块,可以采用如下方法判断文件/目录是否存在。

  • Path(object_path).exists() 判断文件/目录的路径是否存在
  • Path(file_path).is_file() 判断文件是否存在
  • Path(folder_path).is_dir() 判断文件夹是否存在

参考资料:

[1] Python判断文件是否存在的三种方法(https://www.cnblogs.com/jhao/p/7243043.html)

[2] Python 判断文件/目录是否存在(https://www.runoob.com/w3cnote/python-check-whether-a-file-exists.html)

[3] os.path (https://docs.python.org/3/library/os.path.html#module-os.path)

[4] pathlib (https://docs.python.org/3/library/pathlib.html#module-pathlib)

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-03-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 数据处理与编程实践 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1 使用os模块
  • 2 使用pathlib模块
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档