CSV:以純文本形式存儲數據,由任意數目的記錄組成,記錄之間以某種字符分隔ui
1.寫文件編碼
def write_csv(): list1 = [[1, 2, 3], [4, 5, 6]] header = [0, 0, 0] l2 = [7, 8, 9] # utf-8-sig 此種格式能夠用excel打開;newline若是不寫明,每次write後,會自動增長新行。 with open('csv3.csv', 'w', encoding='utf-8-sig', newline='') as f: writer = csv.writer(f) writer.writerow(header) # 寫入一行 writer.writerows(list1) writer.writerow(l2)
2.讀取文件spa
若是不加編碼格式,這裏會報錯:'gbk' codec can't decode byte 0xbf in position 2: illegal multibyte sequence 能夠聲明忽略編碼錯誤:errors='ignore'的,可是讀出來的數據會有亂碼。excel
def read_csv(): with open('csv3.csv', 'r', encoding='utf-8-sig') as f: reader = csv.reader(f) header = next(reader) # 獲取行頭 print(header) for r1 in reader: print(r1)
3.寫入字典code
def write_dict(): header = ['name', 'sex'] dict1 = {'name': "test", 'sex': 18} with open('csv4.csv', 'w', encoding='utf-8-sig', newline='') as f: writer = csv.DictWriter(f, header) # 須要標題,若是沒有會報錯__init__() missing 1 required positional argument: 'fieldnames' writer.writeheader() writer.writerow(dict1) # 能夠寫入單行或者多行 rows
4. 讀取字典blog
def read_dict(): with open('csv4.csv', 'r', encoding='utf-8-sig') as f: reader = csv.DictReader(f) # 無需讀取標題 for row in reader: # 每次讀取一行,返回一個dict print(row['name'], row['sex'])