写入csv文件源码:
#输出数据写入CSV文件
import csv
data = [
("Mike", "male", 24),
("Lee", "male", 26),
("Joy", "female", 22)
] #Python3.4以后的新方式,解决空行问题
with open('d://write.csv', 'w', newline='') as csv_file:
csv_writer = csv.writer(csv_file)
for list in data:
print(list)
csv_writer.writerow(list)
读取csv文件源码:
#读取csv文件内容
import csv
list = []
reader = csv.reader(open("d://demo.csv"))
#csv中有三列数据,遍历读取时使用三个变量分别对应
for title, year, director in reader:
list.append(year)
print(title, "; ", year , "; ", director) print(list)
读取运行结果:
读取csv文件内容更多方式:
# 读取csv文件内容
# date:2017-08-26
import csv file = "d://write.csv" def csv_read(file):
'''
获取每个元素
:param file: 读取文件
:return: 元素列表
'''
with open(file) as file:
list = []
csv_reader = csv.reader(file)
for id, data, *args in csv_reader:
# 跳过表头
if id == " ":
continue
print(id, data)
list.append(data)
return list def csv_read_by_next(file):
'''
逐行取值
:param file: 读取文件
:return: 逐行打印内容(列表形式)
'''
with open(file) as file:
csv_reader = csv.reader(file)
while True:
try:
csv_next_row = next(csv_reader)
except:
break
else:
print(csv_next_row) csv_read_by_next(file)
'''
['Mike', 'male', '24']
['Lee', 'male', '26']
['Joy', 'female', '22']
'''