I have an assignment to write a Python script which "detects whether the file is readable or not".
I am stuck as to which exceptions I should run. Let's say the input file is intended to be a text file, with extension *.txt
What is the exception I should raise? I suspect there should be multiple. At the moment, I have:
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
However, that only checks the file extension. What else could I possibly check? What is the standard for file I/O in Python?
To check whether the file exists:
import os.path
if os.path.exists('example_file.txt'):
print('it exists!')
Beyond this, successfully open
ing the file will demonstrate readability. The built-in open
raises an IOError
exception if it fails. Failure can occur for more than one reason, so we must check whether it failed due to readability:
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.