Hackerss.com

hackerss
hackerss

Posted on

Python Read a csv file


import csv

def read_csv(filename):
    """
    Read a csv file.

    Parameters
    ----------
    filename : str
        The name of the file to read.

    Returns
    -------
    list of lists
        The contents of the file.
    """

    #create an empty list to store the data
    data = []

    #open the file
    with open(filename, 'r') as f:

        #create a csv reader object
        reader = csv.reader(f)

        #loop over the rows in the csv file
        for row in reader:

            #add each row to the list
            data.append(row)

    #return the list of lists
    return data

#example
data = read_csv('data.csv')
#output
print(data)  #[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)