繁体   English   中英

如何在不打开文件的情况下测试文件在python中是否可读?

[英]How to test if a file is readable in python without opening the file?

想要通过检查文件的属性/权限来测试文件在Linux系统上的python中是否可读。

python的新手,我正在perl / bash中寻找以下内容的等效项。

[[-r $ {filename}]]

要么

如果(-r $ filename){...}

我只是打开文件以检查其可读性:

def isFileReadable2 (filename):
    # check to see if file is readable
    # by trying to open a file in readonly mode
    # if an exception occurs,
    # then either the file didnt exist, or file was NOT readable
    try:
        import stat
        mode = os.stat(filename).st_mode
        fh = open (filename, 'r')
    except IOError as err:
        print ("Error opening file {}:{}\n". format (filename, err))
    else:
        fh.close ()
        return True
    return False

我确实注意到stat_result的位模式与文件许可权相对应,即st_mode = 32832转换为0b1000000001000000,这反过来告诉我该文件仅是用户可执行文件,而根本不可读,恰好是正确的。

因此,尽管我可以使用适当的位掩码进行检查,但是os.stat_result对象是否有更好的可移植接口? 特别是st_mode值?

考虑使用os.fstat,但是返回相同的stat_result对象。

tia,

您可以使用函数os.access

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM