Home > Back-end >  How to add file not found function on my script when csv file is not existing on the path
How to add file not found function on my script when csv file is not existing on the path

Time:05-20

Would like to add an print statement which triggers when the csv file is not existing on directory, May I know what I need to add on my script?

SPREADSHEET_ID = 'SAMPLE_SPREADSHEETI1234'
worksheet_name = 'CSVimport'
credentials = 'pdkey123.json'
for my_csv in glob.glob('/home/pdadmin/MYProject.csv':
    print ('CSV file found!')
    print (my_csv)

Export script

def export_csv(my_csv, sheet_id):
    with open(my_csv, 'r') as csv_file:
      csvContents = csv_file.read()
    body = {
        'requests': [{
            'pasteData': {
                "coordinate": {
                    "sheetId": sheet_id,
                    "rowIndex": "0",
                    "columnIndex": "0",
                },
                "data": csvContents,
                "type": 'PASTE_NORMAL',
                "delimiter": ',',

CodePudding user response:

You can use os utilities.

Here's the code you asked for:

import glob 
import os


def export_csv(my_csv, sheet_id):
    if os.path.exists(my_csv):
        with open(my_csv, 'r') as csv_file:
            csvContents = csv_file.read()
        body = {
            'requests': [{'pasteData': {
                    "coordinate": {
                        "sheetId": sheet_id,
                        "rowIndex": "0",
                        "columnIndex": "0",
                    },
                "data": csvContents,
                "type": 'PASTE_NORMAL',
                "delimiter": ','
                }}] 
            }
        # ... SUCCESS_TRIGGER
        # 
        print(body)
    else:
        # ... FILE_NOT_FOUND_TRIGGER
        raise FileNotFoundError()


SPREADSHEET_ID = 'SAMPLE_SPREADSHEETI1234'
worksheet_name = 'CSVimport'
credentials = 'pdkey123.json'
for my_csv in glob.glob('/home/pdadmin/MYProject.csv'):
    try:
        export_csv(my_csv, 1)
        print('CSV file found!')
    except FileNotFoundError:
        print('CSV file NOT found!')

CodePudding user response:

The issue when using for in loop in this case is that when it doesn't match anything (file not existing), it won't proceed as the returned list would be empty. You could check first if the returned list is not empty. If it is not empty, then process your data, else, print something.

Once in the for in, we are sure all files are present as glob.glob will match only existing files.

import os
import glob

SPREADSHEET_ID = 'SAMPLE_SPREADSHEETI1234'
worksheet_name = 'CSVimport'
credentials = 'pdkey123.json'
path = '/home/pdadmin/MYProject.csv';

if len(csv_list := glob.glob(path)):
  for my_csv in csv_list:
    print(f"{my_csv} file found!")
    export_csv(my_csv, SPREADSHEET_ID)
else:
  print(f"{path} not found!")

You can also modify the path to use a pattern so it catches multiple files and export them one by one. Just add an asterisk as wildcard within the path.

  • Related