Python read a line of csv

Suppose the CSV file content is as follows:

No.,Name,Age,Score
1,Apple,12,98
2,Ben,13,97
3,Celia,14,96
4,Dave,15,95

Save it as "A.csv". Using the  csv module that comes with Python  , there are two ways to extract a row:

Method 1: reader

The first method uses the reader function, which receives an iterable object (such as a csv file) and returns a generator, from which the content of the csv can be parsed: for example, the following code can read the entire content of the csv, in order to act unit:

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

get:

[['No.', 'Name', 'Age', 'Score'],
['1', 'Apple', '12', '98'],
['2', 'Ben', '13', '97'],
['3', 'Celia', '14', '96'],
['4', 'Dave', '15', '95']]

To extract the second row, use the following code:

import csv
with open('A.csv','rb') as csvfile:
    reader = csv.reader(csvfile)
    for i,rows in enumerate(reader):
        if i == 2:
        row = rows
print row 

get:

['2', 'Ben', '13', '97']

This method is a general method. The row number must be known in advance. For example, Ben's record is in row 2, and cannot be queried based on the name 'Ben'. In this case, the second method can be used:

Method 2: DictReader

The second method is to use DictReader, which is similar to the reader function. It receives an iterable object and returns a generator, but each cell returned is placed in the value of a dictionary, and the key of this dictionary is this The title of the cell (ie the column header). The structure of DictReader can be seen with the following code:

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

get:

[{'Age': '12', 'No.': '1', 'Score': '98', 'Name': 'Apple'},
{'Age': '13', 'No.': '2', 'Score': '97', 'Name': 'Ben'},
{'Age': '14', 'No.': '3', 'Score': '96', 'Name': 'Celia'},
{'Age': '15', 'No.': '4', 'Score': '95', 'Name': 'Dave'}]

If we want to use DictReader to read a certain column of csv, we can use the column title to query:

import csv
with open('A.csv','rb') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        if row['Name']=='Ben':
        print row

just get:

{'Age': '13', 'No.': '2', 'Score': '97', 'Name': 'Ben'}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325856579&siteId=291194637