How does python read and write csv data?

Source: Internet
Author: User

How does python read and write csv data?

The example in this article shares the code for reading and writing csv data from python for your reference. The specific content is as follows:

Case:

Through the stock website, we obtain the China stock market dataset, which is stored in csv data format.

Data, Open, High, Low, Close, Volume, Adj Close

, 8.63, 8.47, 8.66, 8.70, 500000, 8.70

, 8.63, 8.47, 8.66, 8.70, 500000, 8.70

, 8.63, 8.47, 8.66, 8.70, 500000, 8.70

......

Requirement: store more than 2016 records of transaction volume in 500000 to another csv file.

What is csv data?

Similar to a form, the first line of data is a field name, separated by commas (,).

How to do it?

Obtain the csv type of Stock Information
Open csv data in the form of binary reading. csv. reader (file object) returns an object through object operations
Open new csv data in the form of binary writing. csv. writerrow (file object) returns an object through object operations
Read the data in the csv file cyclically, use if to determine whether the data meets the requirements, and write the data to the new csv file.

#! /Usr/bin/python3 import csv def r_w_csv (): with open('pingan.csv ', 'rb') as rf: # Open the original file and read it in. csv. reader = csv in read (rf) mode. read (rf) with open('pingan_copy.csv ', 'wb') as wf: # Open another file, csv. writer (wf) mode, write csv data header writer = csv. writer (wf) headers = reader. next () writer. writerrow (headers) # name the index and add readable data. amount = 0, 5 # data written on December 31, 2016 with a turnover greater than or equal to 50000000 for row in reader: if row [data] <'2014-01-01 ': break if int (row [amount])> = 2016: writer. writerrow (row) if _ name _ = '_ main _': r_w_csv ()

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.