主要是講我寫**的時候,出現的幾處小錯誤
import csv
def csv_read():
with open("student.csv") as f:
readers = csv.reader(f)
header = next(readers)
print(header)
for list in readers:
print(list)
if __name__ == '__main__':
csv_read()
執行失敗:
traceback (most recent call last):
file "e:/python/try_02/try_csv.py", line 14, in csv_read()
file "e:/python/try_02/try_csv.py", line 7, in csv_read
header = next(readers)
unicodedecodeerror: 'gbk' codec can't decode byte 0xbf in position 2: illegal multibyte sequence
正確方法:在開啟檔案時,指定編碼格式,引數encoding用來指定編碼格式
import csv
def csv_read():
with open("student.csv", encoding = "utf-8") as f:
readers = csv.reader(f)
header = next(readers)
print(header)
for list in readers:
print(list)
if __name__ == '__main__':
csv_read()
輸出:
['\ufeff"sno"', 'sname', 's***', 'sdept', 'sage']
['08001', '張力', '男', '軟體', '18']
['08002', '張麗', '女', '**', '20']
['08003 ', '李梅', '女 ', '藝設', '19']
['08004', '**', '女', '外國語', '18']
['08005', '趙雷', '男', '生化', '19']
['08006', '王語嫣 ', '女', '軟體', '18']
['08007', '趙海', '男', '數學', '19']
['08008 ', '劉晨', '男', '計科', '18']
['08009', '劉丹丹', '女', '**', '18']
['08010', '高曉', '女', '藝設', '19']
['08011', '王江', '男', '生化', '20']
['08012', '嚴格', '男', '機械', '18']
['08013', '崔鍵', '男', '機械', '19']
['08014', '張果', '男', '數學', '19']
['08015', '李嚴', '女', '軟體', '19']
可以觀察到輸出時出現了『\ufeff』,把編碼格式更改為『utf-8-sig』,去除『\ufeff』
'\ufeff'用來標識檔案的位元組序
另外兩種讀取csv檔案的方法:
# namedtuple()相等於建立了乙個student型別的類 需要匯入模組
def csv_namedtuple_read():
with open("student.csv", encoding="utf-8-sig") as f:
content = csv.reader(f)
header = next(content)
student = namedtuple("student", header)
for row in content:
stu = student(*row)
print(stu)
# 讀取csv到字典表中
def csv_dict_read():
with open("student.csv", encoding = "utf-8-sig") as f:
students = csv.dictreader(f)
for stu in students:
print(stu)
讀取CSV檔案資料練習
import csvfrom matplotlib import pyplot as plt from datetime import datetime 讀取csv檔案資料 filename sitka weather 2014.csv with open filename as f 開啟這個檔案,...
c 讀取csv到陣列 python讀取csv檔案
python讀取csv檔案 csv檔案,用記事本編輯,然後命名為test1.csv 1,2,3,4 5,6,7,8 9,10,11,12 用excel開啟,就是這樣的 使用python讀取檔案 按行讀取。然後把讀到的東西賦值給python程式中的變數。這個變數,可以是乙個列表 在這裡,是乙個2維的列...
讀取 CSV 檔案
csv檔案 即 csv comma separate values 用逗號分隔值,可以用excel開啟檢視 由於是純文字,任何編輯器都快可以開啟檢視.與excel不同的是,在csv檔案中 1.值沒有型別,所有值都是字串 2.不能指定字型顏色等樣式 3.不能指定單元格的寬高,不能合併單元格 4.沒有多...