读取csv文件
一、创建一个csv文件
['city', 'password', 'day']
['1', '1', '1']
['2', '1', '1']
['3', '1', '1']
['4', '1', '1']
['5', '1', '1']
二、读取csv文件
import csv
#打开一个csv文件,模式为读取
csvfile = open('/Users/yanghui/Study/python/example.csv','r')
#定义一个变量,进行读取
readCSV = csv.reader(csvfile)
print(readCSV)
#分行打印
for row in readCSV:
print(row)
#读取第一行第二个元素
readCSV = csv.reader(csvfile)
rows = [row for row in readCSV]
print(rows[0][1])
#获取第一行第二个元素
readCSV = csv.reader(csvfile)
for i,rows in enumerate(readCSV):
if i == 0:
row = rows
print(rows[1])
#每列输出打印
readCSV = csv.reader(csvfile)
list1 = []
list2 = []
list3 = []
for row in readCSV:
list1.append(row[0])
list2.append(row[1])
list3.append(row[2])
print(list1)
print(list2)
print(list3)
1 import csv
2 #打开文件,用with打开可以不用去特意关闭file了,python3不支持file()打开文件,只能用open()
3 with open("XXX.csv","r",encoding="utf-8") as csvfile:
4 #读取csv文件,返回的是迭代类型
5 read = csv.reader(csvfile)
6 for i in read:
7 print(i)
————————————————————————————————————————————————————————
写入csv文件
import csv
#打开一个csv文件,模式为写,如果没有该文件,则创建一个
with open('/Users/yanghui/Study/python/test.csv','a') as csvfile:
#定义一个写变量
writeCSV = csv.writer(csvfile)
writeCSV.writerow(['id','kebi','17'])
13.1.4. Writer Objects
Writer
objects (DictWriter
instances and objects returned by the writer()
function) have the following public methods. A row must be a sequence of strings or numbers for Writer
objects and a dictionary mapping fieldnames to strings or numbers (by passing them through str()
first) for DictWriter
objects. Note that complex numbers are written out surrounded by parens. This may cause some problems for other programs which read CSV files (assuming they support complex numbers at all).
csvwriter.
writerow
(row)
Write the row parameter to the writer’s file object, formatted according to the current dialect.
csvwriter.
writerows
(rows)
Write all elements in rows (an iterable of row objects as described above) to the writer’s file object, formatted according to the current dialect.
Writer objects have the following public attribute:
csvwriter.
dialect
A read-only description of the dialect in use by the writer.
DictWriter objects have the following public method:
参考 https://docs.python.org/2/library/csv.html#writer-objects