How to read first line of CSV file

Question:

I’m trying to write a simple python code for taking in a csv file, and using tabulate module to print out nicely-formatted contents in the terminal. Here is snippet of my code:

table = []
try:
    with open(filename) as csvfile:
        reader = csv.DictReader(csvfile)
        i = 0
        for row in reader:
            if (i == 0):
                headers = row
                i = 1
            table.append(row)
except FileNotFoundError:
    print("File not found.")
    sys.exit()
#output
print(tabulate(table, headers, tablefmt='grid'))

When I run the code, it prints out the table, but is using the second line in the csv file for the headers instead of the first line. This makes first two rows of output duplicates.

Basically, how to store the first row of the .csv file as the table headers?

Based on the help provided, I have fixed my code by changing to the following. Now, it works. Thank you.

table = []
try:
    with open(filename, newline='') as csvfile:
        reader = csv.DictReader(csvfile)
        headers = reader.fieldnames
        for row in reader:
            table.append(list(row.values()))
except FileNotFoundError:
    print("File not found.")
    sys.exit()

#output
print(tabulate(table, headers, tablefmt='grid'))
Asked By: Doug

||

Answers:

See the csv.DictReader docs, in particular the second paragraph. If you don’t use a fieldnames parameter (which you didn’t), the resulting dict’s keys (fieldnames) are the values in the first row of the CSV file. You can access the fieldnames in your code using reader.fieldnames.

Your code should look something like this:

table = []
try:
    with open(filename) as csvfile:
        reader = csv.DictReader(csvfile)
        headers = reader.fieldnames
        for row in reader:
            table.append(row)
except FileNotFoundError:
    print("File not found.")
    sys.exit()
#output
print(tabulate(table, headers, tablefmt='grid'))
Answered By: MattDMo

The only thing I can think of is that your program somehow assumes the first row as headers. Typically .csv files have headers as the first line. So what I would do is probably get rid of

if(i == 0)

and its content to just directly append the row.

Answered By: James Hou
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.