Python读写csv文件
分类:
Python(63)
版权声明:本文为博主原创文章,未经博主允许不得转载。
1. 写入并生成csv文件
代码:
# coding: utf-8
import csv
csvfile = file('csv_test.csv', 'wb')
writer = csv.writer(csvfile)
writer.writerow(['姓名', '年龄', '电话'])
data = [
('小河', '25', '1234567'),
('小芳', '18', '789456')
]
writer.writerows(data)
csvfile.close()
- wb中的w表示写入模式,b是文件模式
- 写入一行用writerow
- 多行用writerows
2. 读取csv文件
代码:
# coding: utf-8
import csv
csvfile = file('csv_test.csv', 'rb')
reader = csv.reader(csvfile)
for line in reader:
print line
csvfile.close()
运行结果:
root@he-desktop:~/python/example# python read_csv.py
['\xe5\xa7\x93\xe5\x90\x8d', '\xe5\xb9\xb4\xe9\xbe\x84', '\xe7\x94\xb5\xe8\xaf\x9d']
['\xe5\xb0\x8f\xe6\xb2\xb3', '25', '1234567']
['\xe5\xb0\x8f\xe8\x8a\xb3', '18', '789456']
-
顶
- 4
-
踩
- 10
参考知识库
-
Python知识库
18547关注|1269收录
- 猜你在找
3楼 哈士奇说喵 2016-09-17 12:07发表 [回复]-
-
多谢zengITzeng
2楼 zengITzeng 2013-12-31 15:02发表 [回复]-
-
导入codecs模块,解决excel无法识别中文的问题
1楼 zengITzeng 2013-12-31 15:01发表 [回复]-
-
# coding: utf-8
import csv
import codecs
csvfile = file('csv_test.csv', 'wb')
csvfile.write(codecs.BOM_UTF8)
writer = csv.writer(csvfile)
writer.writerow(['姓名', '年龄', '电话'])
data = [
('С曾', '25', '1234567'),
('С李', '18', '789456')
]
writer.writerows(data)
csvfile.close()