The company wants me to make reports, but I feel a sense of crisis because I only have random data charts, so let’s try Python to read csv

Python read csv


Insert picture description here


Output all lines

import csv
with open("GDP_MAP.csv","r") as f:
    reader=csv.reader(f)
    rows=[row for row in reader]
print(rows)

Insert picture description here

Insert picture description here

Output a certain column [Don’t worry, output all columns, let’s try it later]

import csv
with open("GDP_MAP.csv","r") as f:
    reader=csv.reader(f)
    rows=[row[0] for row in reader]
print(rows)

Insert picture description here

This outputs the first column.

Output all columns

import csv
global total
with open("GDP_MAP.csv","r") as k:
    reader = csv.reader(k)
    rows3 = [row for row in reader]
    row_1=[]
    row_1=rows3[0]
    #print(row_1)
    total=len(row_1)
    #print(total)
for i in range(0,total):
    with open("GDP_MAP.csv","r") as f:
            reader=csv.reader(f)
            rows2 = [row[i] for row in reader]
            print(rows2)

Because there is no fixed reading of all the built-in functions, the idea is to read a row, determine the number of elements, let me know how many columns there are, and then use the loop for assignment output, which is equivalent to obtaining the output of all the columns.

DictReader output dictionary

import csv
with open('GDP_MAP.csv','r') as csvfile:
    reader = csv.DictReader(csvfile)
    rows = [row for row in reader]
print(rows)

Insert picture description here

DictReader output available dictionaries

import csv
with open('GDP_MAP.csv','r') as csvfile:
    reader=csv.reader(csvfile)
    fieldnames=next(reader)
    csv_reader = csv.DictReader(csvfile,fieldnames=fieldnames)
    for row in csv_reader:
        d={
    
    }
        for k,v in row.items():
            d[k]=v
        print (d)

Insert picture description here

That's it for the introduction.

Guess you like

Origin blog.csdn.net/XRTONY/article/details/114904216