Python itself comes with csv module, refer to the online manual: http://docs.python.org/2/library/csv.html1. Use python to read csv files:Csv is a comma-separated format. Generally, the format generated by execl is xls and xlsx. If you rename it to csv directly, an Error is returned: Error: line contains NULL byteinsun solution: the error is caused by renaming the execl file suffixed with xls to csv. If it is saved as a csv file, no error is reported. For example, we have a csv file:
#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-
ImpOrt csv
With open('egg.csv ', 'rb') as f:
Reader = csv. reader (f)
For row in reader:
Print row
The output is a list ['A', '1', '1', '1'] ['A', '2', '2 ', '2'] ['B', '3', '3', '3'] ['B', '4', '4 ', '4'] ['B', '5', '5', '5'] ['B', '6', '6 ', '6'] ['C', '7', '7', '7'] ['C', '8', '8 ', '8'] ['C', '9', '9', '9'] ['C', '10', '10 ', '10'] ['D', '11', '11', '11'] ['E', '12', '12 ', '12'] ['E', '13', '13', '13'] ['E', '14', '14', '14']
2. Write and generate csv files in python
#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-
ImpOrt csv
With open('egg2.csv ', 'wb') as csvfile:
Spamwriter = csv. writer (csvfile, delimiter = '',
Quotechar = '|', quoting = csv. QUOTE_MINIMAL)
Spamwriter. writerow (['A', '1', '1', '2', '2'])
Spamwriter. writerow (['B', '3', '3', '6', '4'])
Spamwriter. writerow (['C', '7', '7', '10', '4'])
Spamwriter. writerow (['D', '11', '11', '11', '1'])
Spamwriter. writerow (['E', '12', '12', '14', '3'])
In this way, we store a column of csv files which are not the same as the original intention to store 5 columns. If we use python csv to generate csv files compatible with excel, it mainly means that when the writer is created, dialect = 'excel 'is required'
#!/usr/bin/env python
#-*-Coding: UTF-8 -*-
ImpOrt csv
With open('egg2.csv ', 'wb') as csvfile:
Spamwriter = csv. writer (csvfile, dialect = 'excel ')
Spamwriter. writerow (['A', '1', '1', '2', '2'])
Spamwriter. writerow (['B', '3', '3', '6', '4'])
Spamwriter. writerow (['C', '7', '7', '10', '4'])
Spamwriter. writerow (['D', '11', '11', '11', '1'])
Spamwriter. writerow (['E', '12', '12', '14', '3'])
This time meets our requirements.
3. Practice:Http://zhidao.baidu.com/question/529653801.html? Push = 1 & group = 1
I want to use python to process csv data.
Calculate the minimum number of the first case of a, the minimum value of the second column, and the maximum value of the third column.
B, c, d, e, etc.
Figure 1 shows figure 2 (the last column is the number of AH, a, B, c, d, and e)