![](/img/trans.png)
[英]Python TypeError: '_csv.writer' object is not iterable
[英]Encountering TypeError with csv.writer
我正在編寫一個腳本來幫助我處理.csv文件。 目的是讀取指定的.csv,然后將數據拆分為幾個臨時文件以進行進一步操作。 輸入.csv中的空白行(空字符串列表)表示我要在哪里拆分數據。
如果我的代碼無法在PEP 8中運行,我深表歉意。Python(就此而言,通常是編碼)對我來說還是很新的。
import os
import csv
import tempfile
def importFromCSV(filepath):
print("Reading data from",os.path.basename(filepath))
datalist = []
with open(filepath) as csvfile:
file_dialect = csv.Sniffer().sniff(csvfile.readline(),[',',';',':','\t','.'])
csvfile.seek(0)
filereader = csv.reader(csvfile,dialect = file_dialect)
for row in filereader:
datalist.append(row)
return datalist
def SplitToTemp(datalist, target_dir):
tmpnamelist = []
templist = []
for item in datalist:
if item[0] != '':
templist.append(item)
else:
del item
f = tempfile.NamedTemporaryFile(delete = False, dir = target_dir)
tmpnamelist.append(f.name)
dw = csv.writer(f, delimiter = ',', quotechar = '|', quoting = csv.QUOTE_MINIMAL)
for row in templist:
dw.writerow(row)
f.close()
templist = []
return tmpnamelist
###############################################################################
pathname = os.path.normpath('C:/Python33/myprograms/myclassandfx/BenchLink/blrtest.csv')
tempdir = tempfile.mkdtemp(dir = os.path.normpath('c:/users/'+os.getlogin()+'/desktop'))
filedata = import_from_csv(pathname)
tempnames = SplitToTemp(filedata, tempdir)
但是,當我運行代碼時,會遇到以下問題:
Traceback (most recent call last):
File "C:\Python33\myprograms\myclassandfx\BenchLink\BenchLinkReader_classless.py", line 56, in <module>
tempnames = SplitToTemp(filedata, tempdir)
File "C:\Python33\myprograms\myclassandfx\BenchLink\BenchLinkReader_classless.py", line 45, in SplitToTemp
dw.writerow(row)
TypeError: 'str' does not support the buffer interface
令我感到困惑的部分是,當我執行print(temp)
,我仍然得到列表列表。
我在這里做錯了什么?
默認情況下,以二進制模式打開tempfile.NamedTemporaryFile()
對象。 引用文檔 :
mode參數默認為
'w+b'
以便可以在不關閉文件的情況下讀寫創建的文件。 使用二進制模式,因此它在所有平台上均表現一致,而無需考慮存儲的數據。
您需要改為以文本模式打開它:
f = tempfile.NamedTemporaryFile(mode='w+', delete=False, dir=target_dir)
當dw.writerow()
方法嘗試將unicode str
值寫入僅支持bytes
的文件對象(支持緩沖區接口的對象)時,將引發錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.