2014-01-13 23 views
0

我正在編寫腳本來幫助我處理.csv文件。目標是讀取指定的.csv文件,然後將數據拆分爲多個臨時文件以供進一步操作。輸入.csv中的空行(空字符串列表)表示我想要分割數據的位置。csv.writer與Encountering TypeError

如果我的代碼針對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),我仍然得到列表的列表部分。

我在這裏做錯了什麼?

回答

0

tempfile.NamedTemporaryFile()對象打開二進制模式,默認情況下;從documentation引述:

模式參數默認爲'w+b'以便創建的文件可以被讀取並且沒有被關閉寫入。使用二進制模式,以便在所有平臺上保持一致,而不考慮存儲的數據。

您需要在文本模式下打開它來代替:當dw.writerow()方法試圖寫的unicode str值到一個文件對象將只支持bytes(支持對象拋出

f = tempfile.NamedTemporaryFile(mode='w+', delete=False, dir=target_dir) 

錯誤緩衝接口)。

+0

謝謝!我想我應該仔細看一下'tempfile'文檔... – PolskiPhysics