Python 判断文件是否存在:os.path.exists() 使用指南

在 Python 编程中,经常需要检查某个文件是否存在,才能进行后续操作。这时,os.path.exists() 函数就派上用场了。

os.path.exists() 函数的作用

os.path.exists() 函数用于判断指定路径的文件或文件夹是否存在。

  • 如果路径存在,则返回 True
  • 如果路径不存在,则返回 False

使用方法

import os

file_path = 'path/to/file.txt'

if os.path.exists(file_path):
    print('文件存在')
else:
    print('文件不存在')

代码解析

  1. 首先,我们导入 os 模块。
  2. 接着,定义变量 file_path 并赋值为要检查的文件路径。
  3. 调用 os.path.exists() 函数,传入 file_path 作为参数。
  4. 根据函数返回值,使用条件语句判断文件是否存在,并打印相应信息。

示例

假设我们要检查 'C:/Users/User/Desktop/test.txt' 文件是否存在,可以这样写:

import os

file_path = 'C:/Users/User/Desktop/test.txt'

if os.path.exists(file_path):
    print('文件存在')
else:
    print('文件不存在')

总结

os.path.exists() 函数是 Python 文件操作中非常实用的函数,可以帮助我们轻松判断文件或文件夹是否存在,避免程序出错。熟掌握该函数的使用方法,将提升你的 Python 文件处理能力。

Python 判断文件是否存在:os.path.exists() 使用指南

原文地址: https://www.cveoy.top/t/topic/dUSR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录