Python检查文件是否存在 - 使用os.path.exists()
使用Python检查文件是否存在
在Python中处理文件时,经常需要检查文件是否存在。这可以通过 os 模块中的 os.path.exists() 函数轻松完成。
os.path.exists() 函数
os.path.exists(path) 函数用于检查给定路径是否存在。路径可以是文件或目录。
- 如果路径存在,则返回
True。 - 如果路径不存在,则返回
False。
示例
以下是如何使用 os.path.exists() 函数检查文件是否存在的示例:
import os
filename = 'example.txt'
if os.path.exists(filename):
print('文件存在')
else:
print('文件不存在')
在这个例子中:
- 我们将文件名存储在变量
filename中。 - 我们使用
os.path.exists()函数检查文件是否存在。 - 如果文件存在,则打印'文件存在',否则打印'文件不存在'。
这是一个简单易用的方法,用于使用Python检查文件是否存在。
原文地址: https://www.cveoy.top/t/topic/dURk 著作权归作者所有。请勿转载和采集!