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?
- Get the CSV type data for stock information
- Open CSV type data as binary read, Csv.reader (file descriptor) Returns an object that is manipulated by an object
- Opens new CSV data as binary write, Csv.writerrow (file descriptor) Returns an object that is manipulated by an object
- 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