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.