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)
,我仍然得到列表的列表部分。
我在這裏做錯了什麼?
謝謝!我想我應該仔細看一下'tempfile'文檔... – PolskiPhysics