欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入免费知识星球。

Python 查看文件或目录是否存在

Python基础 迷途小书童 2年前 (2021-08-23) 968次浏览 0个评论

环境

  • windows 10 64bit
  • python 3.7.9

方法一

通过打开文件的结果来判断,此文件是否存在

try:
    f = open("filename.txt")
except FileNotFoundError:
    # 不存在时做什么事
else:
    # 存在时做什么事

方法二

使用 os.path 模块来判断,比方法一简单好用,文件 io 毕竟是个耗时操作

import os

if os.path.exists('filename.txt'):
    # 文件或目录存在时,做什么事
else:
    # 不存在时做什么事

if os.path.isfile('filename.txt'):
    # 是文件做什么事

if os.path.isdir('filename'):
    # 是目录做什么事

方法三

python 3.4版本开始,可以使用 pathlib 这个库来处理,无需特别处理各平台的路径(/\)问题。以上三种方法中,也是推荐使用这种。

from pathlib import Path

the_file = Path('filename.txt')

if the_file.is_file():
    # 是文件做什么事

if the_file.is_dir():
    # 是目录做什么事

if the_file.exists():
    # 文件或目录存在时,做什么事
喜欢 (0)

您必须 登录 才能发表评论!

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

请关闭 Adblock 等类似浏览器插件,然后刷新页面访问,感谢您的支持!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.