Python中csv文件操作
Posted 知我几分
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python中csv文件操作相关的知识,希望对你有一定的参考价值。
1.csv写入
"""csv两种写入操作""" import csv def write_csv_demo(): headers = ["username", "age", "height"] values = { ("张三", 18, 180), ("李四", 19, 190), ("王五", 20, 160) } # 写入编码utf-8防止乱码,newline默认 换行,防止换行让它等于空字符串 with open("classroom.csv", "w", encoding="utf-8", newline="") as fp: # 创建一个文件句柄对象 writer = csv.writer(fp) # 写入一行writerow writer.writerow(headers) # 写入多行writerows writer.writerows(values) def write_csv_site(): headers = ["username", "age", "height"] values = [ {"username": "张三", "age": 18, "height": 180}, {"username": "李四", "age": 19, "height": 190}, {"username": "王五", "age": 20, "height": 160}, ] with open("classroom1.csv", "w", encoding="utf-8", newline="") as fp: # DictWriter需要传入一个文件句柄和字典的key列表 writer = csv.DictWriter(fp, headers) # 正式写入需要调用writeheader方法 writer.writeheader() writer.writerows(values) if __name__ == ‘__main__‘: write_csv_site()
2.csv读取
"""读取csv文件的两种方式""" import csv def read_csv_demo(): # 优势:操作简单。劣势:数据排序混乱时取值可能报错 with open("classroom.csv", "r", encoding="utf-8") as fp: # reader是一个迭代器 reader = csv.reader(fp) # 执行一次next,指针跳过一位,可以不获取标题 next(reader) for x in reader: print(x) # 可用列表下标x[1]获取具体对象 def read_csv_site(): # 优势:即便数据混乱也可以通过key取值。劣势:稍复杂一点 with open("classroom1.csv", "r", encoding="utf-8") as fp: # 使用DictReader创建的reader对象不会包含标签这一行的数据 reader = csv.DictReader(fp) # 遍历reader迭代器返回的是一个有序字典 for x in reader: value = {"name": x["username"], "age": x["age"]} print(value) if __name__ == ‘__main__‘: read_csv_site()
以上是关于Python中csv文件操作的主要内容,如果未能解决你的问题,请参考以下文章
对关闭的 csv 文件 ValueError 的操作,Python 代码