How to Read and Display a CSV File in a Table Format

76 views

How to Read and Display a CSV File in a Table Format

How to Read and Display a CSV File in a Table Format

I have a CSV file and I want to read and display its contents as a table in Python.

solveurit24@gmail.com Changed status to publish February 16, 2025
0

You can use the csv module to read the file and the tabulate library to format it as a table.

  1. Install tabulate:
    • Use pip to install the library.
    pip install tabulate
    
  2. Read and Display CSV as Table:
    • Read the CSV file and convert it into a list of lists.
    • Use tabulate() to format the data as a table.
  3. Code Example:

    import csv
    from tabulate import tabulate
    
    with open('data.csv', 'r') as file:
        reader = csv.reader(file)
        data = list(reader)
        print(tabulate(data, headers='firstrow', tablefmt='grid'))
    


  4. Sample CSV File (data.csv):
    Name,Age,City
    Alice,30,New York
    Bob,25,Los Angeles
    Charlie,35,Chicago
    
  5. Output:
    +----------+-----+-------------+
    | Name     | Age | City        |
    +==========+=====+=============+
    | Alice    |  30 | New York    |
    | Bob      |  25 | Los Angeles |
    | Charlie  |  35 | Chicago     |
    +----------+-----+-------------+
    
  6. Explanation:
    • tabulate provides various table formats for better readability.
    • The headers='firstrow' parameter specifies that the first row contains table headers.
solveurit24@gmail.com Changed status to publish February 16, 2025
0