官方文档: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()
读取
要读取的文件
# MontyPythonAlbums.csv
Name,Year
Monty Python's Flying Circus,1970
Another Monty Python Record,1971
Monty Python's Previous Record,1972
# 按行读取列表
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()