department-for-transport-BODS / bods-data-extractor

A python client for downloading and extracting data from the UK Bus Open Data Service
Other
44 stars 8 forks source link

Uncaught exception in create_today_folder function (otc_db_download) (4) #81

Open EOstridge opened 1 year ago

EOstridge commented 1 year ago

Issue

def create_today_folder():
    '''
    Create a folder, named with the days data, so that timetables can be saved locally
    '''

    today = str(date.today())
    downloads_folder = get_user_downloads_folder()

The above will result in an uncaught exception if downloads doesn't exist. There is a print message earlier in the code (Line 31) which goes some way to helping the user, however it won't appear in the StackTrace.

Suggested Approach

One suggestion for a better approach would be to:

  1. Remove the else block from Line 30
  2. Enclose the rest of the function in a try/catch (catch the specific exception) - first, allow the user to choose a download folder; if still an exception, set the exception error message to the message at Line 31.

Refactoring

    # list out the file names in the downloads folder
    files = os.listdir(downloads_folder)

    # create the path for today folder in downloads
    today_folder_path = downloads_folder + '/' + today

    # if timetable output folder is not in downloads, create
    if today not in files:
        os.mkdir(today_folder_path)

    else:
        print('file with todays date already exists')

    return today_folder_path

Please replace the above with one of the following code options for best practice - the user doesn't need a feedback message.

Use: https://www.tutorialspoint.com/How-can-I-create-a-directory-if-it-does-not-exist-using-Python

Please combine steps for neater code wherever possible.

# list out the file names in the downloads folder
    files = os.listdir(downloads_folder)

The above isn't needed as you would use path.exists(path) instead.

adamakram1 commented 1 year ago

.