1. 程式人生 > >python csv模組寫檔案 出現 iterable expected, not int 錯誤

python csv模組寫檔案 出現 iterable expected, not int 錯誤

開始程式碼:

import csv
def storFile(data,fileName):
    with open(fileName,'w',newline ='') as f:
        mywrite = csv.writer(f)
        for i in data:
            mywrite.writerow(i)
data = [1,0,1,1,0,1,0]
storFile(data,'splitData\wodecesi.csv')

報錯:
<ipython-input-33-5de04d85deaa> in storFile(data, fileName)
      4         mywrite = csv.writer(f)
      5         for i in data:
----> 6             mywrite.writerow(i)
      7 data = [1,0,1,1,0,1,0]
      8 storFile(data,'splitData\wodecesi.csv')

Error: iterable expected, not int

查閱資料發現: csv 的writerow 函式只能寫入一個序列,比如 list 或 array.

修改方法:

(1) 直接讀取整個列表:fsdg

import csv
def storFile(data,fileName):
    with open(fileName,'w',newline ='') as f:
        mywrite = csv.writer(f)
        mywrite.writerow(data)
data = [1,0,1,1,0,1,0]
storFile(data,'splitData\wodecesi.csv')

所得csv檔案中,列表元素為 1  0  1  1  0  1  0  排列;

(2)先將每個元素轉換為小列表,再儲存:

import csv
def storFile(data,fileName):
    data = list(map(lambda x:[x],data))
    with open(fileName,'w',newline ='') as f:
        mywrite = csv.writer(f)
        for i in data:
            mywrite.writerow(i)
data = [1,0,1,1,0,1,0]
storFile(data,'splitData\wodecesi.csv')
(3)使用pands的to_csv 函式:
data.to_csv('splitData\wodecesi.csv',index = False)

(2)和(3)所得檔案中,元素為縱向排列:

1

0

1

1

0

1

0