• python 中 os.path.exists() try 判断文件是否存在于当前目录


    使用OS模块

    import os                    #   加入模块

    filename = 'path_file/file.txt'     #将某一路径下(path_file)的文件(flie.txt)

    os.path.exists(filename)        #使用函数exists()对文件存在与否进行判断,存在为True,不存在为False.

    也可以在脚本中,加入if语句判断 是否存在文件,从而进行下一步的操作或者返回信息

    if os.path.exists(filename) == True:            #即文件存在

       print(‘file.txt 文件存在’)

    else:                                                                

      print('file.txt文件不存在‘’)

    当文件存在后,对文件的内容进行判断,是否可以读写等操作

    使用的是os.access()方法判断文件是否可以进行读写操作

    os.access(path, mode)     # 文件的路径(path),操作模式(mode):文件是否存在 (os.F_OK) ,可读(os.R_OK),可写(os.W_OK),可执行(os.X_OK)

    使用Try对文件open()打开,根据反馈的是否有ERROR来进行判断文件是否存在

    try:

        f = open(path_file)                   # 打开path路径下的file文件

        f.close()                                   #通常对文件读取完后,进行关闭文件

    except IOError:

        print(“path_file 不存在”)

  • 相关阅读:
    由于媒体16摘要天
    vim note (2)
    JEECG 什么是商业版本的功能最近添加的好友?
    图解linux启动过程
    Error: unrecognized flag -version
    基于RDP瘦客户机协议的简要说明
    Android在网络上分析获取图片(支持bmp格式)
    [React] Validate Custom React Component Props with PropTypes
    [Python] Wikipedia Crawler
    [Python] Python list slice syntax fun
  • 原文地址:https://www.cnblogs.com/wh-ff-ly520/p/13360762.html
Copyright © 2020-2023  润新知