python - How to read multiple files with error checking? -
i have function reads multiple files. this:
try: = open("1.txt", "r") b = open("2.txt", "r") c = open("3.txt", "r") except ioerror: print("file {:s} failed".format(a, b or c)) i want can see file failed during reading it. can somehow specify ioerror specified file? mean if ioerror appears in file a, "command1", if in file b, "command2" , on?
the ioerror exception alias of oserror exception, has filename attribute. can use switch behaviour based on file failed:
try: = open("1.txt", "r") b = open("2.txt", "r") c = open("3.txt", "r") except oserror error: print("file {:s} failed".format(error.filename)) i used name oserror; ioerror deprecated , kept around backwards compatibility, see pep 3151.
demo:
>>> try: ... open('nonesuch.txt') ... except oserror error: ... print('file {:s} failed'.format(error.filename)) ... file nonesuch.txt failed note open() call throws exception, no assignment has taken place. , because file object can referenced multiple places, including list, there no way map file object or filename name going assign to. if wanted know of a, b or c file object have been bound to, you'd have create own mapping:
filenames = {'1.txt': 'a', '2.txt': 'b', '3.txt': 'c'} print("file {} failed".format(filenames[error.filename]))
Comments
Post a Comment