How to Read and Display a CSV File in a Table Format
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
You can use the csv module to read the file and the tabulate library to format it as a table.
- Install
tabulate:- Use pip to install the library.
pip install tabulate - 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.
- 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'))
- Sample CSV File (
data.csv):Name,Age,City Alice,30,New York Bob,25,Los Angeles Charlie,35,Chicago - Output:
+----------+-----+-------------+ | Name | Age | City | +==========+=====+=============+ | Alice | 30 | New York | | Bob | 25 | Los Angeles | | Charlie | 35 | Chicago | +----------+-----+-------------+ - Explanation:
tabulateprovides 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