Python_ how to read and write CSV data

Source: Internet
Author: User

Case:

Through the stock website, we acquired the Chinese stock market data set, which is stored in CSV data format.

Data,open,high,low,close,volume,adj Close

2016-06-28,8.63,8.47,8.66,8.70,500000,8.70

2016-06-28,8.63,8.47,8.66,8.70,500000,8.70

2016-06-28,8.63,8.47,8.66,8.70,500000,8.70

......

Requirements: store 2016 volume more than 500000 records in another CSV file

What is CSV type data?

Similar to the form, the first row of data is the field name, separate data separated by commas

How to do?

  1. Get the CSV type data for stock information
  2. Open CSV type data as binary read, Csv.reader (file descriptor) Returns an object that is manipulated by an object
  3. Opens new CSV data as binary write, Csv.writerrow (file descriptor) Returns an object that is manipulated by an object
  4. loops through the data in CSV, through if to determine whether to meet the requirements, to satisfy the write to the new CSV file
    #!/ Usr/bin/python3import csvdef r_w_csv (): With open (' pingan.csv ', ' RB ') as RF: # Open the original file read in, Csv.read (RF) mode R            Eader = Csv.read (RF) with open (' Pingan_copy.csv ', ' WB ') as WF: # Open another file, Csv.writer (WF) way, write to the CSV data header                        writer = Csv.writer (wf) headers = Reader.next () writer.writerrow (headers)  # name index, increase readability data, amount = 0, 5 # write Time 2016, turnover greater than or equal to 50000000 for row In Reader:if Row[data] < ' 2016-01-01 ': Break if int (Row[amount]) = 50000000:writer.writerrow (row) if __name__ = = ' __main__ ': r_w_csv () 

Python_ How to read and write CSV data

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.