python读取写入csv文件
【摘要】 csv文件 读取保存操作
官方文档:https://docs.python.org/3/library/csv.html
写入
# -*- encoding: utf-8 -*-
import csv
from io import StringIO
from urllib import urlopen
# 按行元组参数写入
def writerCsv1(): ...
csv文件 读取保存操作
官方文档:https://docs.python.org/3/library/csv.html
写入
# -*- encoding: utf-8 -*-
import csv
from io import StringIO
from urllib import urlopen
# 按行元组参数写入
def writerCsv1(): f = open("data.csv", "w") writer = csv.writer(f) for i in range(100): writer.writerow((i+1, i+2, i+3)) f.close()
# 按行字典参数写入
def writerCsv2(): f = open("data.csv", "w") writer = csv.DictWriter(f, ["name", "age"]) for i in range(100): dct = {"name":i+1, "age": i+2} writer.writerow(dct) f.close() print("写入成功!")
writerCsv2()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
读取
要读取的文件
# MontyPythonAlbums.csv
Name,Year
Monty Python's Flying Circus,1970
Another Monty Python Record,1971
Monty Python's Previous Record,1972
- 1
- 2
- 3
- 4
- 5
- 6
# 按行读取列表
def readerCsv1(): # 读取网络文件 # url = "http://www.pythonscraping.com/files/MontyPythonAlbums.csv" # data = urlopen(url).read() # 读取本地文件 data = open("MontyPythonAlbums.csv", "r").read().decode('utf-8') print type(data) data_file = StringIO(data) # 字符串转为io对象 csv_reader = csv.reader(data_file) for row in csv_reader: print(row) """ ['Name', 'Year'] ["Monty Python's Flying Circus", '1970'] """
# readerCsv1()
# 按行读取列表
def readerCsv2(): f = open("MontyPythonAlbums.csv", "r") csv_reader = csv.reader(f) for row in csv_reader: print(row) """ ['Name', 'Year'] ["Monty Python's Flying Circus", '1970'] """ f.close()
# readerCsv2()
# 按行读取字典,第一行为key
def readerCsv3(): f = open("MontyPythonAlbums.csv", "r") csv_reader = csv.DictReader(f) for row in csv_reader: print(row) # {'Name': "Monty Python's Flying Circus", 'Year': '1970'} f.close()
# readerCsv3()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。
原文链接:pengshiyu.blog.csdn.net/article/details/79917825
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)