Python’s “open()” throws different errors for “file not found” – how to handle both exceptions?

In 3.3, IOError became an alias for OSError, and FileNotFoundError is a subclass of OSError. So you might try except (OSError, IOError) as e: … This will cast a pretty wide net, and you can’t assume that the exception is “file not found” without inspecting e.errno, but it may cover your use case. PEP 3151 … Read more

What can lead to “IOError: [Errno 9] Bad file descriptor” during os.system()?

You get this error message if a Python file was closed from “the outside”, i.e. not from the file object’s close() method: >>> f = open(“.bashrc”) >>> os.close(f.fileno()) >>> del f close failed in file object destructor: IOError: [Errno 9] Bad file descriptor The line del f deletes the last reference to the file object, … Read more

Can’t Open files from a directory in python [duplicate]

listdir returns just the file names: https://docs.python.org/2/library/os.html#os.listdir You need the fullpath to open the file. Also check to make sure it is a file before you open it. Sample code below. for filename in os.listdir(seqdir): fullPath = os.path.join(seqdir, filename) if os.path.isfile(fullPath): in_file = open(fullPath,’r’) #do you other stuff However for files it is better to … Read more