1.什么是csv文件
The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. CSV format was used for many years prior to attempts to describe the format in a standardized way in RFC 4180.
2.csv文件缺点
The lack of a well-defined standard means that subtle differences often exist in the data produced and consumed by different applications. These differences can make it annoying to process CSV files from multiple sources. Still, while the delimiters and quoting characters vary, the overall format is similar enough that it is possible to write a single module which can efficiently manipulate such data, hiding the details of reading and writing the data from the programmer.
3.python模块csv.py
The csv
module implements classes to read and write tabular data in CSV format. It allows programmers to say, “write this data in the format preferred by Excel,” or “read data from this file which was generated by Excel,” without knowing the precise details of the CSV format used by Excel. Programmers can also describe the CSV formats understood by other applications or define their own special-purpose CSV formats.
the csv
module’s reader
and writer
objects read and write sequences. Programmers can also read and write data in dictionary form using the DictReader
and DictWriter
classes
reader(csvfile[, dialect='excel'][, fmtparam])
csvfile
需要是支持迭代(Iterator)的对象,并且每次调用next方法的返回值是字符串(string),通常的文件(file)对象,或者列表(list)对象都是适用的,如果是文件对象,打开是需要加"b"标志参数。
dialect
编码风格,默认为excel方式,也就是逗号(,)分隔,另外csv模块也支持excel-tab风格,也就是制表符(tab)分隔。其它的方式需要自己定义,然后可以调用register_dialect方法来注册,以及list_dialects方法来查询已注册的所有编码风格列表。
fmtparam
格式化参数,用来覆盖之前dialect对象指定的编码风格。
参数解释:
delimiter:设置分隔符
quotechar:设置引用符
quoting:引号选项,有4种不同的引号选项
在csv模块中定义为四个变量:
QUOTE_ALL不论类型是什么,对所有字段都加引号。
QUOTE_MINIMAL对包含特殊字符的字段加引号(所谓特殊字符是指,对于一个用相同方言和选项配置的解析器,可能会造成混淆的字符)。这是默认选项。
QUOTE_NONNUMERIC对所有非整数或浮点数的字段加引号。在阅读器中使用时,不加引号的输入字段会转换为浮点数。
QUOTE_NONE输出中所有内容都不加引号。在阅读器中使用时,引号字符包含在字段值中(正常情况下,它们会处理为定界符并去除)。
import csv
def testReader(file):
with open(file, 'r') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',')
for row in spamreader:
print(', '.join(row))
if __name__ == '__main__':
csvFile = 'test.csv'
testReader(csvFile)
writer(csvfile[, dialect='excel'][, fmtparam])
参数表(略: 同reader, 见上)
def testWriter(file):
with open(file, 'w') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
DictReader(f,fieldnames = None,restkey = None,restval = None,dialect ='excel',* args,** kwds )
创建一个像常规阅读器一样操作的对象,但将每一行中的信息映射到一个OrderedDict
由可选的fieldnames参数给出的键。
字段名的参数是一个序列。如果省略字段名称,文件f的第一行中的值将用作字段名称。无论字段名称如何确定,有序字典保留其原始排序。
如果一行的字段数超过了字段名,剩下的数据将被放在一个列表中,并与restkey(默认为None
)指定的字段名一起存储。如果非空行的字段数少于字段名,则缺少的值将被填入None
。
def testDictReader(file):
# 院系,专业,年级,学生类别,班级,学号,姓名,学分成绩,更新时间,班级排名,参与班级排名总人数
with open(file, 'rb') as csvfile:
dictreader = csv.DictReader(csvfile)
for row in dictreader:
print(' '.join([row['院系'], row['专业'], row['学号'], row['姓名']]))
DictWriter(f,fieldnames,restval =“,extrasaction ='raise',dialect ='excel',* args,** kwds )
创建一个像普通writer一样运行的对象,但将字典映射到输出行上。的字段名的参数是一个sequence
标识,其中在传递给字典值的顺序按键的writerow()
方法被写入到文件 ˚F。可选的restval参数指定字典缺少字段名中的键时要写入的值。如果传递给该writerow()
方法的字典包含在字段名称中未找到的键 ,则可选的extrasaction参数指示要执行的操作。如果设置为'raise'
默认值,ValueError
则为a 。如果设置为'ignore'
,字典中的额外值将被忽略。任何其他可选或关键字参数都传递给底层 writer
实例。
请注意,与DictReader
类不同,fieldnames参数DictWriter
不是可选的。由于Python的dict
对象未被排序,因此没有足够的可用信息推导出行应该写入文件f的顺序。
def testDictWriter(file):
with open(file, 'w') as csvfile:
fieldnames = ['院系', '专业', '年级', '学生类别', '班级', '学号']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow(
{'院系': '信息学院', '专业': '计算机科学与技术', '年级': '2011级', '学生类别': '本科(本科)4年', '班级': '计算机11', '学号': '201101245'})
writer.writerow(
{'院系': '信息学院', '专业': '计算机科学与技术', '年级': '2011级', '学生类别': '本科(本科)4年', '班级': '计算机11', '学号': '201101275'})
4.示例代码
csv文件的拷贝
def copycsv(source, target):
csvtarget = open(target, 'w+')
with open(source, 'r') as csvscource:
reader = csv.reader(csvscource, delimiter=',')
for line in reader:
writer = csv.writer(csvtarget, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
writer.writerow(line)
csvtarget.close()
5.其他方式(numpy,pandas)
import numpy
my_matrix = numpy.loadtxt(open("num.csv", "rb"), delimiter=",", skiprows=0)
print(my_matrix)
import pandas as pd
obj=pd.read_csv('test.csv')
print obj
print type(obj)
print obj.dtypes
test.csv
院系,专业,年级,学生类别,班级,学号,姓名,学分成绩,更新时间,班级排名,参与班级排名总人数
信息学院,计算机科学与技术,2011级,本科(本科)4年,计算机11,201101244,栾,86.72,2017/9/5 9:59,1,27
信息学院,计算机科学与技术,2011级,本科(本科)4年,计算机11,201101237,刘,86.05,2017/9/5 9:59,2,27
信息学院,计算机科学与技术,2011级,本科(本科)4年,计算机11,201101233,刘,86.03,2017/9/5 9:59,3,27
信息学院,计算机科学与技术,2011级,本科(本科)4年,计算机11,201101250,李,85.43,2017/9/5 9:59,4,27
信息学院,计算机科学与技术,2011级,本科(本科)4年,计算机11,201101229,张,82.35,2017/9/5 9:59,5,27
信息学院,计算机科学与技术,2011级,本科(本科)4年,计算机11,201101241,韩,80.92,2017/9/5 9:59,6,27
信息学院,计算机科学与技术,2011级,本科(本科)4年,计算机11,201101232,丁,80.66,2017/9/5 9:59,7,27
信息学院,计算机科学与技术,2011级,本科(本科)4年,计算机11,201101228,张,79.61,2017/9/5 9:59,8,27
信息学院,计算机科学与技术,2011级,本科(本科)4年,计算机11,201101255,孟,79.55,2017/9/5 9:59,9,27
num.csv
1,2,3
4,5,6
7,8,9
6.完整代码
# coding:utf-8
import csv
def testReader(file):
with open(file, 'r') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',')
for row in spamreader:
print(', '.join(row))
def testWriter(file):
with open(file, 'w') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
def copycsv(source, target):
csvtarget = open(target, 'w+')
with open(source, 'r') as csvscource:
reader = csv.reader(csvscource, delimiter=',')
for line in reader:
writer = csv.writer(csvtarget, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
writer.writerow(line)
csvtarget.close()
def testDictReader(file):
# 院系,专业,年级,学生类别,班级,学号,姓名,学分成绩,更新时间,班级排名,参与班级排名总人数
with open(file, 'rb') as csvfile:
dictreader = csv.DictReader(csvfile)
for row in dictreader:
print(' '.join([row['院系'], row['专业'], row['学号'], row['姓名']]))
def testDictWriter(file):
with open(file, 'w') as csvfile:
fieldnames = ['院系', '专业', '年级', '学生类别', '班级', '学号']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow(
{'院系': '信息学院', '专业': '计算机科学与技术', '年级': '2011级', '学生类别': '本科(本科)4年', '班级': '计算机11', '学号': '201101245'})
writer.writerow(
{'院系': '信息学院', '专业': '计算机科学与技术', '年级': '2011级', '学生类别': '本科(本科)4年', '班级': '计算机11', '学号': '201101275'})
def testpandas_csv():
import pandas as pd
obj = pd.read_csv('test.csv')
print obj
print type(obj)
print obj.dtypes
def testnumpy_csv():
import numpy
my_matrix = numpy.loadtxt(open("num.csv", "rb"), delimiter=",", skiprows=0)
print(my_matrix)
if __name__ == '__main__':
# csvFile = 'test.csv'
# testReader(csvFile)
# csvFile = 'test2.csv'
# testWriter(csvFile)
# copycsv('test.csv', 'testcopy.csv')
# testDictReader('test.csv')
# testDictWriter('test2.csv')
testnumpy_csv()
# testpandas_csv()