Python reads a row of CSV

Source: Internet
Author: User

The webmaster uses Python to write a code that can extract any column of CSV, welcome to use. GitHub links

CSV is the abbreviation for comma-separated values, which is a form of tabular data stored in a text file, such as the following table:

Can be stored as a CSV file with the following file contents:
No.,Name,Age,Score
1,Apple,12,98
2,Ben,13,97
3,Celia,14,96
4,Dave,15,95

Assuming that the above CSV file is saved as "a.csv", how to extract one row in Python like Excel, which is a record, using Python's own CSV module, there are two ways to do this:

The first method uses the reader function to receive an iterative object (such as a CSV file) that returns a generator from which the contents of the CSV can be parsed: for example, the following code can read the entire contents of the CSV in the behavior 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 line, you can 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 common method, in order to know the line number, such as Ben's record in line 2nd, and not according to the name ' Ben ' query. In this case, the second method can be used:

The second approach is to use Dictreader, similar to the reader function, to receive an iterative object that returns a generator, but each cell returned is placed within the value of a dictionary, and the Key of the dictionary is the header (that is, the column header) of the cell. Use the following code to see the structure of the Dictreader:
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 column of CSV, we can query the column header:
import csv
with open(‘A.csv‘,‘rb‘) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        if row[‘Name‘]==‘Ben‘:
            print row
Will get:
{‘Age‘: ‘13‘, ‘No.‘: ‘2‘, ‘Score‘: ‘97‘, ‘Name‘: ‘Ben‘}As you can see, the Dictreader is good for reading the Rows (records) of the CSV.

Csv

The CSV file format is a common spreadsheet and database import and export format. When I recently called RPC to process server data, I often needed to archive the data to use this handy format.

Brief introduction

The Python CSV module encapsulates common functionality, using the following simple examples:

# 读取csv文件import csvwith open(‘some.csv‘, ‘rb‘) as f: # 采用b的方式处理可以省去很多问题 reader = csv.reader(f) for row in reader: # do something with row, such as row[0],row[1]import csvwith open(‘some.csv‘, ‘wb‘) as f: # 采用b的方式处理可以省去很多问题 writer = csv.writer(f) writer.writerows(someiterable)

By default, read and write use commas to make delimiters (delimiter), double quotation marks as the reference (QuoteChar), and when you encounter a special case, you can manually specify the characters as needed, for example:

import csvwith open(‘passwd‘, ‘rb‘) as f: reader = csv.reader(f, delimiter=‘:‘, quoting=csv.QUOTE_NONE) for row in reader: print row

The preceding example specifies a colon as a delimiter and specifies that the quote method is not referenced. This means that the content is not surrounded by the default reference (") when it is read. The optional options for quoting are: QUOTE_ALL, QUOTE_MINIMAL, QUOTE_NONNUMERIC, QUOTE_NONE .

It is important to note that when writing data in writer, it is written as an None empty string, and the floating-point type is converted to a string by the calling repr() method. Therefore, data that is not string-type is str() stored as a string. So when it comes to Unicode strings, it can be stored manually or by using CSV, as described UnicodeWriter here.

Read and write in dictionary mode

CSV also provides a dictionary-like way of reading and writing, as follows:

The format is as follows:

class csv.DictReader(csvfile, fieldnames=None, restkey=None, restval=None, dialect=‘excel‘, *args, **kwds)class csv.DictWriter(csvfile, fieldnames, restval=‘‘, extrasaction=‘raise‘, dialect=‘excel‘, *args, **kwds)

Where fieldnames specifies the key value of the dictionary, if reader does not specify the default first line of the element, in writer must specify this.

Using the example

# Read>>>Import CSV>>>With open (' Names.csv ')As CSVFile:... reader = csv. Dictreader (CSVFile)...For rowIn reader:.. print (row[' First_Name '], row[' Last_Name ') ... Baked beanslovely spamwonderful Spam# Writeimport csvwith Open ( ' names.csv ',  W ') as csvfile:fieldnames = [ ' first_name ',  ' last_name '] writer = csv. Dictwriter (CSVFile, Fieldnames=fieldnames) Writer.writeheader () writer.writerow ({ "first _name ':  ' Baked ',  ' last_name ':  ' first_name ':  ' lovely ',  ' last_name ':  ' Spam '} "Writer.writerow ({ ' First_ Name ':  ' Wonderful ',  ' last_name ':                
Other

The CSV module also deals with other concepts, such as Dialects providing error handling and exception csv.Error so on, because the actual usage is less and is not burdensome here. See the official documentation for more information.

Python reads a row of CSV

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.