Python读写CSV文件

总是忘记如何读写csv,整理一下来加强记忆

  • 读 csv文件
    假设有csv文件内容为:
    id,score
    1,100
    2,80
import csv
data = open("xxx.csv",'r')
dataline = csv.reader(data)
for i in dataline:
    # csv中每一行被转换为了list形式并被赋给i
    print i 
    #>>> ["id", "score"]
    #>>> ["1","100"]
    #>>> ["2","80"]
词典读入
import csv
data = open("xxx.csv",'r')
dict_reader = csv.DictReader(data)
for i in dict_reader:
    print i 
    #>>> {'score': '100', 'id': '1'}
    #>>> {'score': '80', 'id': '2'}

某一列

import csv
data = open("xxx.csv",'r')
dict_reader = csv.DictReader(data)
col_score = [row['score'] for row in dict_reader]
  • 写csv文件
import csv
csvfile = open("yyy.csv", 'w')
csvwrite = csv.writer(csvfile)
fileHeader = ["id", "score"]
d1 = ["1", "100"]
d2 = ["2", "80"]
writer.writerow(fileHeader)
writer.writerow(d1)
writer.writerow(d1)
csvFile.close()

续写

import csv
add_info = ["3", "70"]
csvFile = open("yyy.csv", "a")
writer = csv.writer(csvFile)
writer.writerow(add_info)
csvFile.close()

你可能感兴趣的:(python)