CSV文件,是一種常用的文本格式,Because of its simple format、兼容性好,被廣泛使用,Especially for converting data between programs.
python也內置了csv模塊,用來讀寫csv文件.
一、csv模塊寫入數據
語法:writer(csvfile, dialect=‘excel’,**fmtparams)
csvfile:文件對象
dialect:編碼風格,默認為是excel,也就是用逗號(,)分隔,Generally don't change it.
**fmtparams:dialect格式參數,有delimter(分隔符,默認為逗號)
實例1:The simplest without any parameters,Write a line of data directly–writerrow()
import csv
# 要寫入的數據
data = ['wdewd', '2343243', 'python內置csv模塊學習']
with open('test.csv', 'w') as f:
mywrite = csv.writer(f) # 返回一個writer對象
mywrite.writerow(data) # Write data line by line
結果如下:
注:open()The function opens the filename under the current pathtest.csv的文件,If there is no name under the current pathtest.csv的文件,則會創建它.
實例2:一次寫入多行數據—writerows()
import csv
# 創建一個二維列表,as the data to be written
data_list = []
for i in range(3):
data = [i, 'wdewd', '2343243', 'python內置csv模塊學習']
data_list.append(data)
with open('test.csv', 'w') as f:
mywrite = csv.writer(f) # 返回一個writer對象
mywrite.writerows(data_list) # 一次寫入多行數據
結果如下:
常見問題:When writing multiple rows of data,There is a blank line for each piece of data that appears
解決辦法:在open()函數打開文件時,加一個newline=’’參數即可.
更改後代碼:
import csv
# 創建一個二維列表,as the data to be written
data_list = []
for i in range(3):
data = [i, 'wdewd', '2343243', 'python內置csv模塊學習']
data_list.append(data)
with open('test.csv', 'w', newline='') as f:
mywrite = csv.writer(f) # 返回一個writer對象
mywrite.writerows(data_list) # 一次寫入多行數據
結果如下:
二、csv模塊讀取數據
語法:reader(csvfile, dialect=‘excel’, **fmtparams),參數含義同上.
實例1:讀取剛剛寫入的csv文件
import csv
with open('test.csv', 'r') as f:
res = csv.reader(f)
print('返回一個對象:', res)
print('轉換為列表格式:', list(res))
結果如下:
常見使用問題:
with open('test.csv', 'rb') as f:
res = csv.reader(f)
print('返回一個對象:', res)
print('轉換為列表格式:', list(res))
**錯誤原因:**使用了“b”二進制文件打開模式,csv文件是文本文件,不是二進制文件.
**解決辦法:**使用“r”(默認是t)或者“rt”文件打開模式
常見文件打開模式: