python读写csv⽂件⽅法详细总结
python提供了⼤量的库,可以⾮常⽅便的进⾏各种操作,现在把python中实现读写csv⽂件的⽅法使⽤程序的⽅式呈现出来。
在编写python程序的时候需要csv模块或者pandas模块,其中csv模块使不需要重新下载安装的,pandas模块需要按照对应的
python版本安装。
在python2环境下安装pandas的⽅式是:
sudo pip install pandas
在python3环境下安装pandas的⽅式是:
sudo pip3 install pandas
1、使⽤csv读写csv⽂件⽅法总结
读⽂件的时候,打开⽂件,调⽤ader()读取⽂件;对于读取之后的⽂件的内容,要把这些内容输⼊
到另⼀个⽂件中保存,可以通过遍历读取的⽂件的每⼀⾏,然后使⽤csv_write.writerow()的⽅式写⼊到指定的⽂件。
2、使⽤csv读写csv⽂件⽰例代码
#encoding:utf-8
import csv
#读取csv⽂件
csv_file = ader(open('../../data/capital/2010-Q4-cabi-trip-history-data.csv'))
print(csv_file)
#添加newline可以避免⼀⾏之后的空格,这样需要在python3环境下运⾏
out = open('../../data/capital/2010-Q4','a',newline='')
csv_write = csv.writer(out,dialect='excel')
for item in csv_file:
#print item
csv_write.writerow(item)
print("write over")
上⾯的代码是传统的打开⽂件---读取⽂件---打开⽂件---关闭⽂件的⽅式进⾏⽂件读取和写⼊。在读取和写⼊的过程中分别调⽤了csv库的reader()和writer()
3、使⽤csv读写csv⽂件⽰例代码
#encoding:utf-8
import csv
#下⾯这种加了encoding的写法需要在python3环境下运⾏
csv_reader = ader(open('../../data/capital/2011-Q1-cabi-trip-history-data.csv',encoding='utf-8'))
out = open('../../data/capital/a0','w',newline='')
csv_writer = csv.writer(out,dialect='excel')
for row in csv_reader:
#输出的每⼀⾏是⼀个list,list中的每⼀个元素转换成了string类型
print(row)
csv_writer.writerow(row)
⽰例代码2的读写⽅式与⽰例代码1的⽅式基本相同,不同的是在⽰例代码2中打开⽂件的时候指定了打开时的编码⽅式,对于输出⽂件的打开⽅式也与⽰例代码1的⽅式有少量的差别,把写⼊⽅式右'a'改成了'w
4、使⽤csv读写csv⽂件⽰例代码
#encoding:utf-8
import csv
#读取csv⽂件⽅式1
csvFile = open('../../data/capital/2011-Q3-cabi-trip-history-data.csv','r')
reader = ader(csvFile)
data = []
for item in reader:
# print(item)
data.append(item)
#print(data)
csvFile.close()
#读取csv⽂件⽅式2
with open("../../data/capital/2011-Q3-cabi-trip-history-data.csv",'r') as csvFile:
#读取csv⽂件,返回的是迭代类型
reader2 = ader(csvFile)
for item2 in reader2:
print(item2)
csvFile.close()
#从列表写⼊csv⽂件
#设置newline,否则两⾏之间会空⼀⾏
csvFile2 = open('../../data/capital/0001.csv','w',newline='')
writer = csv.writer(csvFile2)
m = len(data)
for i in range(m):
writer.writerow(data[i])
csvFile2.close()
#从字典写⼊csv⽂件
dic = {'张三':123,'李四':456,'王⼆娃':789}
csvFile3 = open('../../data/capital/0001.csv','w',newline='')
writer2 = csv.writer(csvFile3)
for key in dic:
print(key)
# writer2.writerow([key,dic[key]])
csvFile3.close()
在上⾯的代码中提出了两种不同的打开csv⽂件和写⼊csv⽂件的⽅式。其中第⼀种打开⽅式与前⾯两种⾮常相似,不同之处是在这种⽅式中,打开⽂件的时候加⼊了读取⽅式,⽽前⾯两个⽰例代码没有加。另⼀种读取⽅式是采⽤python中独有的命名⽅式对打开⽂件命名,其他部分相似。在这个⽰例中,对列表和字典写⼊csv⽂件做了区分,分别提供了列表和字典写⼊csv⽂件的⽰例代码。
5、使⽤csv读写csv⽂件⽰例代码
#encoding:utf-8
'''
import pandas as pd
#任意的多组列表
a = [1,2,3]
b = [4,5,6]
#字典中的key值即为csv中的列名
dataFrame = pd.DataFrame({'a_name':a,'b_name':b})
#将DataFrame存储为csv,index表⽰是否显⽰⾏名,default=True
<_csv('0001.csv',index=False,sep='')
#pandas提供的读取csv的⽅法
data = pd.read_csv('test.csv')
'''
#===================================
#另⼀种⽅法:⽤csv包,⼀⾏⼀⾏写⼊
import csv
#python2可以⽤file替代open
with open('test.csv','w') as csvFile:
writer = csv.writer(csvFile)
#先写columns_name
writer.writerow(["index","a_name","b_name"])
#写⼊多⾏⽤writerows
writer.writerows([[1,2,3],[0,1,2],[4,5,6]])
#⽤reder读取csv⽂件
with open('test.csv','r') as csvFile:
reader = ader(csvFile)
for line in reader:
print line
这个⽰例代码提出了写⼊⼀⾏和写⼊多⾏的实现⽅式。
6、使⽤csv读写csv⽂件⽰例代码
#encoding:utf-8
import csv
with open('test.csv') as csvFile:
#readcsv = ader(csvFile,delimiter='')
readcsv = ader(csvFile)
#
rows= [row for row in readcsv]
for row in readcsv:
rows= [row for row in reader]
#print(row)#打印⼀⾏
print(row[0])#打印⼀⾏中的某个cell
print(row[0],row[1])#打印⼀⾏中的某个cell
print('=================')
with open('test.csv') as csvFile:
readCSV = ader(csvFile)
cols1 = []
cols2 = []
cols3 = []
for row in readCSV:
col1 = row[0]
col2 = row[1]
col3 = row[2]
cols1.append(col1)
cols2.append(col2)
cols3.append(col3)
print cols1
print cols2
print cols3
上⾯的代码⽰例提出了读取所有⾏的新写法,提出了读取某个cell和某⼀列的⽅式。
7、使⽤csv读写csv⽂件⽰例代码
#encoding:utf-8
import csv
#第⼀种⽅法:使⽤reader函数,接收⼀个可迭代的对象(⽐如csv⽂件),能返回⼀个⽣成器,就可以从其中解析出csv的内容.eg:下⾯的代码可以读取csv的全部内容,以⾏为单位
with open('test.csv','rb') as csvFile:
reader = ader(csvFile)
rows = [row for row in reader]
print rows
print('===========')
#提取其中某⼀列可以使⽤下⾯的⽅法
with open('test.csv','rb') as csvFile:
reader = ader(csvFile)
column = [row[1] for row in reader]
print column
python怎么读csv数据print('======第⼆种⽅法======')
#第⼆种⽅法:使⽤DictReader,和reader函数类似,接收可迭代的对象,能返回⼀个可迭代的对象,能返回⼀个⽣成器,但是返回的每⼀个单元格都放在⼀个字典的值内,⽽这个字典的键则是这个单元格的标题.⽤下⾯的代码可以看到DictReader的结构: with open('test.csv','rb') as csvFile:
reader = csv.DictReader(csvFile)
column = [row for row in reader]
print(column)
#使⽤CictReader读取csv的某⼀列,这样可以按照列的标题查询
with open('test.csv','rb') as csvFile:
reader = csv.DictReader(csvFile)
column = [row['a_name'] for row in reader]
print column
上⾯的代码提出了读取整⾏和整列的新⽅式。另外提出了⼀种使⽤DictReader的⽅式按照列名读取的⽅式。
8、使⽤csv读写csv⽂件⽰例代码
#encoding:utf-8
import csv
with open('test.csv','rb') as csvFile:
reader = ader(csvFile)
for row in reader:
print row
#向csv⽂件中写内容,这样写会把内容全部写到⼀个cell中
with open('test1.csv','wb') as csvFile:
writer = csv.writer(csvFile,delimiter=' ',quotechar='|',quoting=csv.QUOTE_MINIMAL) writer.writerow(['a','4','5','6'])
writer.writerow(['b','1','2','3'])
writer.writerow(['c','9','8','7'])
writer.writerow(['d','8','3','1'])
#向csv⽂件中写内容,下⾯的写法最终可以把每⼀列的内容放在⼀个cell中
with open('test2.csv','wb') as csvFile:
writer = csv.writer(csvFile,dialect='excel')
writer.writerow(['a','4','5','6'])
writer.writerow(['b','1','2','3'])
writer.writerow(['c','9','8','7'])
writer.writerow(['d','8','3','1'])
上⾯的代码提出了可以把列表中的数据放⼊到不同cell的实现⽅式。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论