Use Python to operate the instance code on the Csv file,

Source: Internet
Author: User

Use Python to operate the instance code on the Csv file,

Csv is the abbreviation of Comma-Separated Values. It is the table data stored in the form of text files, such as the following table:

It can be stored as a csv file with the following content:

No.,Name,Age,Score1,mayi,18,992,jack,21,893,tom,25,954,rain,19,80

Assume that the preceding csv file is saved as "test.csv"

1. Read files

How to Use Python to extract a column, that is, a field, like an Excel operation. Using the csv module provided by Python, there are two methods to achieve this:

The first method is to use the reader function to receive an iteratable object (such as a csv file), return a generator, and parse the csv content from it: for example, the following code can read all the contents of csv, in the unit of Behavior:

#! /Usr/bin/python3 #-*-conding: UTF-8-*-_ author _ = 'mayi' import csv # Read with open ("test.csv", "r ", encoding = "UTF-8") as f: reader = csv. reader (f) rows = [row for row in reader] print (rows)

Get:

[['No.', 'Name', 'Age', 'Score'], ['1', 'mayi', '18', '99'], ['2', 'jack', '21', '89'], ['3', 'tom', '25', '95'], ['4', 'rain', '19', '80']]

To extract a column, use the following code:

#! /Usr/bin/python3 #-*-conding: UTF-8-*-_ author _ = 'mayi' import csv # Read the content of the second column with open ("test.csv ", "r", encoding = "UTF-8") as f: reader = csv. reader (f) column = [row [1] for row in reader] print (column)

Get:

['Name', 'mayi', 'jack', 'tom', 'rain']

Note that the str type is read from csv. This method requires you to know the sequence number of the column in advance, for example, the Name is in the 2nd column, but cannot be queried Based on the 'name' title. In this case, the second method can be used:

The second method is to use DictReader, which is similar to the reader function. It receives an iteratable object and can return a generator, but every returned cell is placed in a dictionary value, the dictionary key is the title of the Cell (that is, the column header ). The following code shows the structure of the DictReader:

#-*-Conding: UTF-8-*-_ author _ = 'mayi' import csv # Read with open ("test.csv", "r", encoding = "UTF-8 ") as f: reader = csv. dictReader (f) column = [row for row in reader] print (column)

Get:

[{'No.': '1', 'Age': '18', 'Score': '99', 'Name': 'mayi'}, {'No.': '2', 'Age': '21', 'Score': '89', 'Name': 'jack'}, {'No.': '3', 'Age': '25', 'Score': '95', 'Name': 'tom'}, {'No.': '4', 'Age': '19', 'Score': '80', 'Name': 'rain'}]

If you want to use DictReader to read a csv column, you can use the column title to query:

#! /Usr/bin/python3 #-*-conding: UTF-8-*-_ author _ = 'mayi' import csv # Read the content of the Name column with open ("test.csv ", "r", encoding = "UTF-8") as f: reader = csv. dictReader (f) column = [row ['name'] for row in reader] print (column)

Get:

['mayi', 'jack', 'tom', 'rain']

2. Write files

When reading a file, we read the csv file into the list. When writing a file, we write the elements in the List into the csv file.

#! /Usr/bin/python3 #-*-conding: UTF-8-*-_ author _ = 'mayi' import csv # Write: append row = ['5 ', 'hanmeimei', '23', '81 '] out = open ("test.csv", "a", newline = "") csv_writer = csv. writer (out, dialect = "excel") csv_writer.writerow (row)

Get:

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.