I have the following code:
except(OSError) as (errno, strerror, filename):
print "OSError [%d]: %s at %s" % (errno, strerror, filename)
It runs great unless it meets OSError num. 123 (The file name, directory name, or volume label syntax is incorrect
). then I get the following error at the except code line:
ValueError: need more than 2 values to unpack
It is solved by not using the filename
attribute. However my requirements prevent me from not using this attribute.
Is there another way?
The OSError: (errno 22) invalid argument occurs may also occur when one is trying to save a file. For example: adding an unnecessary semicolon to the filename also causes the error. It is because windows do not allow semi-colons in file names. That was it for OSError: (errno 22) invalid argument.
When handling the errors that occur when trying to create an existing file or trying to use a file that doesn't exist the OSError s that get thrown have a subclass ( FileExistsError, FileNotFoundError ). I couldn't find that subclass for the special case when the filename is too long.
A. The OSError: (errno 22) invalid argument occurs may also occur when one is trying to save a file. For example: adding an unnecessary semicolon to the filename also causes the error. It is because windows do not allow semi-colons in file names.
OSError is a built-in exception in Python and serves as the error class for the os module, which is raised when an os specific system function returns a system-related error, including I/O failures such as “file not found” or “disk full”. Below is an example of OSError: Attention geek!
I have not seen this kind of Exception handling where you are passing the Exception object's attributes to the as clause.
Normally you handle except ExceptionObject as e
and handle the attributes as one would normally handle the attributes of an object.
OSError contains a errno attribute is a numeric error code from errno, and the strerror attribute is the corresponding string and for exceptions that involve a file system path (such as chdir() or unlink()), the exception instance will contain a third attribute, filename, which is the file name passed to the function.
import os
try:
os.chdir('somenonexistingdir')
except OSError as e:
print e.errno
print e.filename
print e.strerror
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With