读写csv文件

Python 2018-12-30 1112

读取csv文件

import csv

with open('test.csv', 'r', encoding='utf-8')as f:  
    # reader是一个迭代器  
    reader = csv.reader(f)  
    # next遍历了1行  
    next(reader)  
    for i in reader:  
        # 返回列表  
        print(i)  

with open('test.csv', 'r', encoding='utf-8') as f:  
    # 使用DictReader创建reader对象不会包含标题这一行  
    # 返回字典  
    reader = csv.DictReader(f)  
    for i in reader:  
        print(i)  
import csv

headers = ["username", "age", 'height']  

# values = [  
#     ('小明', 18, 160),  
#     ('小花', 19, 165),  
#     ('小华', 20, 170),  
# ]  
# # 乱码就指定编码,newline可以避免空格  
# 推荐windows系统下使用utf-8-sig编码,可以解决utf-8编码下excel打开csv文件乱码的问题
# with open('write.csv', 'w', newline='', encodeing="utf-8-sig") as f:  
#     writer = csv.writer(f)  
#     # 插入一条数据  
#     writer.writerow(headers)  
#     # 插入多条数据  
#     writer.writerows(values)  


# 方法2  
values = [  
    {'username':'小明', "age": 18, "height": 160},  
    {'username':'小花', "age":19, "height":165},  
    {'username':'小华', "age":20, "height":170},  
]  
with open('writer.csv', 'w', newline='') as f:  
    writer = csv.DictWriter(f, headers)  
    # 写表头数据时,需要调用writeheader()  
    writer.writeheader()  
    writer.writerows(values) 

追加写入数据

file = open(“./xxx.csv”, ‘a’,newline=‘’)
writer = csv.writer(file)
writer.writerow([‘xxx’,’ xxx’,0,1,2,3])
file.close()

 

标签:Python

文章评论

评论列表

已有0条评论