1

Is there a way to get more specific Error messages in Python? E.g The full error code or at least the line the error occurred on, the exact file that cannot be found rather than a generic "The system cannot find the file specified")

for file in ['C:/AA/HA.csv', 'C:/AA1/HA1.csv']:
 try:
 os.remove(file)
 except OSError as e:
 pass
 print(getattr(e, 'message', repr(e)))
 #print(getattr(e, 'message', repr(e)))
 #print(e.message)
 #print('File Not Removed')

The following prints twice:

FileNotFoundError(2, 'The system cannot find the file specified')

While this is great, is there a way to get more precise error messages for bug fixing?

The following stops the job but gives out in console the exact line being 855 as well as the file directory ''C:/AC/HA.csv''.

os.remove('C:/AA/HA.csv')
Traceback (most recent call last):
 File "C:/ACA.py", line 855, in <module>
 os.remove('C:/AC/HA.csv')
FileNotFoundError: [WinError 2] The system cannot find the file specified: ''C:/AC/HA.csv'' 
asked Nov 5, 2017 at 6:09

1 Answer 1

1

See the traceback module:

import os
import traceback
for file in ['C:/AA/HA.csv', 'C:/AA1/HA1.csv']:
 try:
 os.remove(file)
 except OSError as e:
 traceback.print_exc()

Output:

Traceback (most recent call last):
 File "C:\test.py", line 6, in <module>
 os.remove(file)
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:/AA/HA.csv'
Traceback (most recent call last):
 File "C:\test.py", line 6, in <module>
 os.remove(file)
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:/AA1/HA1.csv'
answered Nov 5, 2017 at 6:19
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.