检测无效文件输入,Python
Detecting for invalid file inputs, Python
我有一个作业要编写 Python 脚本 "detects whether the file is readable or not"。
我不知道应该使用哪些例外 运行。假设输入文件是一个文本文件,扩展名为 *.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的标准是什么?
检查文件是否存在:
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")
relevant section of the docs on file permissions. 请注意,不鼓励在调用 open
之前使用 os.access
检查可读性。
我有一个作业要编写 Python 脚本 "detects whether the file is readable or not"。
我不知道应该使用哪些例外 运行。假设输入文件是一个文本文件,扩展名为 *.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的标准是什么?
检查文件是否存在:
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")
relevant section of the docs on file permissions. 请注意,不鼓励在调用 open
之前使用 os.access
检查可读性。