2

我有一个任务是编写一个“检测文件是否可读”的 Python 脚本。

我不知道应该运行哪些异常。假设输入文件是一个文本文件,带有扩展名*.txt

我应该提出什么例外?我怀疑应该有多个。目前,我有:

with open('example_file.txt") as textfile:
        if not textfile.lower().endswith('.txt'):
            raise argparse.ArgumentTypeError(
                'Not a text file! Argument filename must be of type *.txt')
        return textfile

但是,这只检查文件扩展名。我还能检查什么?Python中文件I/O的标准是什么?

4

1 回答 1

4

检查文件是否存在

import os.path
if os.path.exists('example_file.txt'):
    print('it exists!')

除此之外,成功open读取文件将证明可读性。如果失败,内置open函数会引发异常。IOError失败的原因可能不止一个,所以我们必须检查它是否由于可读性而失败:

import errno
try:
    textfile = open('example_file.txt', 'r')
    textfile.close()
    print("file is readable")
except IOError as e:
    if e.errno == errno.EACCES:
        print("file exists, but isn't readable")
    elif e.errno == errno.ENOENT:
        print("files isn't readable because it isn't there")

The relevant section of the docs on file permissions. Note that the use of os.access to check readability before calling open is discouraged.

于 2015-12-13T22:40:13.000 回答