python学习笔记——读写csv文件

讲的比较详细的一篇文章。推荐,本文山寨于他。

点击打开链接


python中有一个读写csv文件的包,直接import csv即可。利用这个python包可以很方便对csv文件进行操作

CSV的操作就是对列表的操作。

1.导入模块

import csv

2.写入数据

写入并生成csv文件

写文件时会把列表中的元素写入到csv文件中。

#python对csv读写练习范例代码

import csv

#—————写入csv
#文件头,一般就是数据名
fileheader = ["name","score"]
#假设要写入的两行数据
d1 = ["wang","100"]
d2 = ["li","80"]
#写入数据
csv_file = open('csv_test03.csv','w')
writer = csv.writer(csv_file)
#写入的内容都是以列表的形式传入函数
# writer.writerow(fileheader) #逐行写入
# writer.writerow(d1)
# writer.writerow(d2)
writer.writerows([fileheader,d1,d2])  #一次写入多行的函数writerows()
csv_file.close()

name score  
     
wang 100  
     
li 80  
     

追加写入:

import csv

#需要添加的数据行
add_info = ['hoho','50']
#以添加的形式写入文件,设定关键字“a”,表示追加
csv_file = open('csv_test03.csv','a')
#新建对象writer
writer = csv.writer(csv_file)
#写入数据
writer.writerow(add_info)
csv_file.close()

name score
   
wang 100
   
li 80
   
hoho 50
   
hoho 50
   

以字典形式写入DictWriter

import csv
csvFile = open("instance.csv", "w")
# 文件头以列表的形式传入函数,列表的每个元素表示每一列的标识
fileheader = ["name", "score"]
dict_writer = csv.DictWriter(csvFile, fileheader)
# 但是如果此时直接写入内容,会导致没有数据名,所以,应先写数据名(也就是我们上面定义的文件头)。
# 写数据名,可以自己写如下代码完成:
dict_writer.writeheader()
# 之后,按照(属性:数据)的形式,将字典写入CSV文档即可
dict_writer.writerow({"name": "Li", "score": "80"})
csvFile.close()

写入数据时有空行的解决办法:(使用python3)

改写的代码如下,就能正常写入了 

writefile = open('result.csv','w',newline =‘’)
writer = csv.writer(writefile)


3.读取数据

1 / DictReader读取

import csv

csv_file = open('csv_test03.csv','r')
dict_reader = csv.DictReader(csv_file)
for row in dict_reader:
    print(row)
输出的结果是这样的

OrderedDict([('name', 'wang'), ('score', '100')])
OrderedDict([('name', 'li'), ('score', '80')])
OrderedDict([('name', 'hoho'), ('score', '50')])
OrderedDict([('name', 'hoho'), ('score', '50')])

用DictReader输出文件头:

import csv

csv_file = open('csv_test03.csv','r')
dict_reader = csv.DictReader(csv_file)

res = dict_reader.fieldnames
print(res)
结果:

['name', 'score']

2 / 输出成常见python字典对象

import csv

csv_file = open('csv_test03.csv','r')
dict_reader = csv.DictReader(csv_file)

#创建空字典
result = {}
#遍历取值
for item in dict_reader:
    result[item['name']] = item['score']
print(result)
结果:

{'wang': '100', 'li': '80', 'hoho': '50'}


python读取文件事出错:

 'gbk' codec can't decode byte 0xad in position 2742: illegal multibyte sequence 错误的解决办法:


使用notepad++将文件转换成utf-8 无 BOM编码格式后读取

FILE_OBJECT= open('order.log','r', encoding='UTF-8')






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章