How to properly raise a file exception

Related searches

I have below requirements:

  1. Read the files from Directory, need to find files with wildcard search as there are lot of files in the directory.
  2. If file pattern doesn't match, then I need to raise an exception. Please look at the code below. I am struggling with exception.

I am able to search the files with fnmatch function but if file doesn't exist, then I am am struggling with exception. How do I add exception? Please look at the readstatus() function and please help me how do I add exception logic if file does not exist.

import os
import sys
import boto3
from botocore.client import Config
import configparser
import re
import os.path
import glob
import aws_encryption_sdk
import fnmatch
## Initialize the Parameters
def initconfig(input):

    config = configparser.ConfigParser()
    config.read_file(open( 'CONFIG_AIRBILLING.conf'))
    print('Code Name is :'+ input)
    ACCESS_KEY_ID = config.get('ACCESS', 'ACCESS_KEY_ID')
    BUCKET_NAME = config.get('ACCESS', 'BUCKET_NAME')
    SRC_DIR = config.get(input, 'SRC_DIR')
    FILENAME = config.get(input, 'FILENAME')
    print('File Path is:'+FILEPATH)
    TARGET_DIR = config.get(input, 'TARGET_DIR')

## This function will make sure file exist in Source directory
def readstatus():

      for file in os.listdir(SRC_DIR):
        if fnmatch.fnmatch(file,FILENAME+'*.txt'):

## This function will move the files to AWS S3 bucket
def movefiles(result):

    s3 = boto3.resource(
    s3.Bucket(BUCKET_NAME).put_object(Key=TARGET_DIR + '/' + result, Body=result)
    print('***File Moved***')

if __name__ == '__main__':

How about something like this:

The snippet below filters the list of files in the SRC_DIR using the fnmatch and pattern, and returns the list. Then, it checks if the list is empty, i.e. no files matching the pattern were found, it raises an Exception. Otherwise, it goes on ahead processing the individual files.

def readstatus():
  files = list(filter(lambda f: fnmatch.fnmatch(f, FILENAME+"*.txt"), os.listdir(SRC_DIR)))
  if not files:
    raise Exception("Files matching pattern not found!")
  for file in files:

In case the file is not found, you could expect an error like

Traceback (most recent call last):
  File "", line 20, in <module>
  File "", line 10, in readstatus
    raise Exception("Files matching pattern not found!")
Exception: Files matching pattern not found!

How do I raise a FileNotFoundError properly?, This is better than a "Syntax error in file None", but how is it possible to raise the " real" python exception with the proper message, without having to reimplement� Raising exceptions during exceptional conditions Open a Python File window. You see an editor in which you can type the example code. Type the following code into the window — pressing Enter after each line: try: raise ValueError except ValueError: Choose Run→Run Module. You see a Python Shell


def readstatus():
    result = False
    for file in os.listdir(SRC_DIR):
        if fnmatch.fnmatch(file, FILENAME + '*.txt'):
            result = True
            print('****' + file)

    if result != True:
        print("your file doesn't exist")
        #add exception logic here

The Logic is that if the file is matched with the given filename, then result variable will be True, otherwise the result variable will be False.

We use the value of the variable result as a checksum for whether the file existed or not.

8. Errors and Exceptions — Python 3.8.6rc1 documentation, File name and line number are printed so you know where to look in case the It can also be used to print an error message and then re-raise the exception be used in a way that ensures they are always cleaned up promptly and correctly. As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.

If you're using Python 3.4+, consider using pathlib to make a lot of these pains easier.

def readstatus():

    root = pathlib.Path(SRC_DIR)
    for fpath in root.glob(f"{FILENAME}*.txt"):

Python Exceptions: An Introduction – Real Python, You'll see how to raise exceptions and how to handle them with "try/except" blocks. print( 0 / 0 )) File "<stdin>", line 1 print( 0 / 0 )) ^ SyntaxError: invalid syntax. Here is the output: >>> There was an exception. >>>. You can use the raise keyword to signal that the situation is exceptional to the normal flow. For example: x = 5 if x < 10: raise ValueError ('x should not be less than 10!') Notice how you can write the error message with more information inside the parentheses.

19. Exceptions — How to Think Like a Computer Scientist: Learning , If the file doesn't exist, we don't want the program to crash; we want to handle the exception: If our program detects an error condition, we can raise an exception. Whether we complete the statements in the try clause successfully or not, the� begin # raise 'A test exception.' puts "I'm not raising exception" rescue Exception => e puts e.message puts e.backtrace.inspect else puts "Congratulations-- no errors!" ensure puts "Ensuring execution" end. This will produce the following result −.

Python - Exceptions Handling, Python - Exceptions Handling - Python provides two very important features to handle any unexpected Raised when indentation is not specified properly. 24 32.0 451 Traceback (most recent call last): File "", line 9, in <module> print� Being able to catch exceptions is important, but so is the ability to raise exceptions (or throw exceptions) as it is called in Groovy. If you pass a negative number to the Math.sqrt method, it will return a value called NaN Not A Number.

This string contains the name of the methods on the current call stack, together with the file name and line number where the exception was thrown for each method. A StackTrace object is created automatically by the common language runtime (CLR) from the point of the throw statement, so that exceptions must be thrown from the point where the

  • Awesome!! Thank you so much
  • A more pythonic way would be using try: except: clauses. This is exactly what they're intended for.
  • additionally why are you using the strings 'True' and 'False' instead of the constants True and False?
  • @smallpants the problem with using try except clause is that, except only gets executed upon an error, but with the fnmatch.fnmatch() no error occurs even if the files do not match, so instead of creating a logic for raising an exception, why not simply use an if else? Atleast this is my perspective towards this. Alternatively he can create exception's inside the if clause too if he wants that.
  • Thank you Vasu Deo, Adam and smallpants.