首页 > 编程语言 > 详细

python csv文件写入和读出

时间:2019-07-29 12:40:09      阅读:85      评论:0      收藏:0      [点我收藏+]
import csv

headers = ["class", "name", "sex", "height", "year"]
# rows = [
#     [1, ‘xiaoming‘, ‘male‘, 168, 23],
#     [1, ‘xiaohong‘, ‘female‘, 162, 22],
#     [2, ‘xiaozhang‘, ‘female‘, 163, 21],
#     [2, ‘xiaoli‘, ‘male‘, 158, 21]
# ]
# with open("test.csv", "w", newline="") as f:
#     f_csv = csv.writer(f)
#     f_csv.writerow(headers)
#     f_csv.writerows(rows)

# rows = [
#     {‘class‘: 1, ‘name‘: ‘xiaoming‘, ‘sex‘: ‘male‘, ‘height‘: 168, ‘year‘: 23},
#     {‘class‘: 1, ‘name‘: ‘xiaohong‘, ‘sex‘: ‘female‘, ‘height‘: 162, ‘year‘: 22},
#     {‘class‘: 2, ‘name‘: ‘xiaozhang‘, ‘sex‘: ‘female‘, ‘height‘: 163, ‘year‘: 21},
#     {‘class‘: 2, ‘name‘: ‘xiaoli‘, ‘sex‘: ‘male‘, ‘height‘: 158, ‘year‘: 21},
# ]
# with open("test2.csv", "w", newline="") as f:
#     f_csv = csv.DictWriter(f, headers)
#     f_csv.writeheader()
#     f_csv.writerows(rows)

# 列表读取
with open("test2.csv") as f:
    f_csv = csv.reader(f)
    for row in f_csv:
        print(row)

# 字典读取
with open("test2.csv") as f:
    f_csv = csv.DictReader(f)
    for row in f_csv:
        print(row["sex"])

 

python csv文件写入和读出

原文:https://www.cnblogs.com/liuzhanghao/p/11262994.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!