Python read csv
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)
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)
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)
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)
That's it for the introduction.