Search code examples
pythoncsvinputdijkstra

Create module loading input csv files to the app - dijkstra's algorithm


I need to create a function in Python that will read csv files, and when the file is not the correct csv file, it will throw an error message. It is supposed to be one of the application modules related to the dijkstra algorithm. The file consists of 3 columns separate with commas. These are numbers. Rhe first is the starting node, the second is the ending node, and the third is the weight between them.


Solution

  • If you want to keep the csv file clean you should use csv.DictReader() and csv.DictWriter() to read file checking if the file consists of expected columns you can use the following:

    import csv
    table ={'V1':[],'V2':[], 'edge_weight':[]}
    
    with open('test.csv') as csv_file:
        reader = csv.DictReader(csv_file)
        try:
            for row in reader:
                for k in table.keys():
                    if row[k] is not None:
                        table[k].append(row[k])  
                    else:
                        raise Exception
    
        except Exception:
            print('wrong csv file')
    

    If the file does not contain header with names same as dictionary columns or if there are missing values in columns, Exception will be raised. You can specify your own exceptions as well. Defining own exceptions

    Using csv.DictWriter()