基本介绍:-----------------------------------------------------
#第一种方法使用reader函数,接收一个可迭代的对象(比如csv文件),能返回一个生成器,
#就可以从其中解析出csv的内容:比如下面的代码可以读取csv的全部内容,以行为单位: import csv
def readCsvList():
with open('a.csv','rb') as f: reader = csv.reader(f) next = (reader)
for i in reader: print (i) 要提取其中第二行,可以用下面的代码:
这种方法是通用的方法,要事先知道行号
import csv
def readCsvList():
with open('a.csv','rb') as f:
reader = csv.reader(f)
next = (reader)
for i,rows in enumerate(reader):
if i == 2:
row = rows
print row
第二种方法是使用DictReader,和reader函数类似,接收一个可迭代的对象,能返回一个生成器,但是返回的每一个单元格都放在一个字典的值内,
而这个字典的键则是这个单元格的标题(即列头)。用下面的代码可以看到DictReader的结构: import csv
def readCsvDict():
with open('A.csv','rb') as f: reader = csv.DictReader(f) rows = [row for row in reader] #用列表推导式来打印出数据,也可for循环:for i in reader: print(dict(i)) print rows
如果想用DictReader读取csv的某一列,就可以用列的标题查询: import csv
def readCsvDict(): with open('A.csv','rb') as f: reader = csv.DictReader(f) for row in reader: if row['Name']=='标题': print row
封装成函数来使用:========================================
#CSV文件,读取 def read_csv(self): with open(self.csv_filepath,'r',encoding='utf-8') as f: reader = csv.reader(f) next = (reader) for i in reader: print (i) return reader #CSV文件,写入 # def write_csv(self): # with open(self.csv_filepath, 'a', encoding='utf-8',newline='') as file: # csv_write = csv.writer(file, dialect='excel') # csv_items = [[{"userinfo":"qika"}]] #记住格式:[[ ]]双括号,中间插入值会按传入值的样式,否则默认拆开展示如excel样式; # for item in csv_items: # csv_write.writerow(item) # return csv_items def write_csv(self,csv_items): with open(self.csv_filepath, 'a', encoding='utf-8',newline='') as file: csv_write = csv.writer(file, dialect='excel') for item in csv_items: csv_write.writerow(item) return csv_items ''' reader(csvfile, dialect='excel', **fmtparams) writer(csvfile, dialect='excel', **fmtparams) 参数:: csvfile:必须是支持迭代(Iterator)的对象,可以是文件(file)对象或者列表(list)对象 dialect:编码风格,默认为excel的风格默认为excel的风格,也就是用逗号(,)分隔, dialect方式也支持自定义,通过调用register_dialect方法来注册,下文会提到。 fmtparam:格式化参数,用来覆盖之前dialect对象指定的编码风格。 '''