l--*_*''' 8 python csv python-2.x
我正在尝试将列表列表写入新文件,但我收到此错误:
回溯(最近一次调用最后一次):文件"",第1行,在dowork()文件"C:\ Python27\work\accounting\formatting quickbooks file\sdf.py",第11行,在dowork中WriteFile()文件"C :\ Python27\work\accounting\formatting quickbooks file\sdf.py",第71行,在WriteFile中.frite(thefile)TypeError:期望一个字符缓冲区对象
如何将列表列表写入文件?
这就是我写作的方式:
def WriteFile():
global thefile
f = open("output"+'.csv','w')
f.seek(0)
f.write(thefile)
f.close()
Run Code Online (Sandbox Code Playgroud)
如果您需要,这里是完整的来源:
import csv
thefile = []
output = []
def dowork():
sourceFile='e.csv'
thefile=ReadFile(sourceFile)
CleanFile(sourceFile)
ProcessFile()
WriteFile()
def ReadFile(filename):
return list(csv.reader(open(filename, 'rb'), delimiter=',', quotechar='"'))[1:]
def CleanFile(sourceFile):
global thefile
thefiletmp=[]
for i, line in enumerate(thefile):
if line[2]=='':
del thefile[i]
else:
thefiletmp.append(line[4:])
thefile=thefiletmp
def ProcessFile():
global thefile
iCompany=1
iNum=0
iDate=2
iAging=3
iBalance=4
COMPANIES=GetDistinctValues(1)
mytemparray=[]
mytempfile=[]
for company in COMPANIES:
for line in thefile:
if line[iCompany]==company:
mytemparray.append(line[iCompany])
mytemparray.append(line[iNum])
mytemparray.append(line[iDate])
if line[2] in range(0,31):
mytemparray.append(line[iBalance])
mytemparray.append('0')
mytemparray.append('0')
mytemparray.append('0')
if line[2] in range(31,61):
mytemparray.append('0')
mytemparray.append(line[iBalance])
mytemparray.append('0')
mytemparray.append('0')
if line[2] in range(61,91):
mytemparray.append('0')
mytemparray.append('0')
mytemparray.append(line[iBalance])
mytemparray.append('0')
if line[2] >90:
mytemparray.append('0')
mytemparray.append('0')
mytemparray.append('0')
mytemparray.append(line[iBalance])
mytempfile.append(mytemparray)
mytemparray=[]
thefile=mytempfile
def WriteFile():
global thefile
f = open("output"+'.csv','w')
f.seek(0)
f.write(thefile)
f.close()
def GetDistinctValues(theColumn):
return sorted(list(set(line[theColumn] for line in thefile)))
Run Code Online (Sandbox Code Playgroud)
aba*_*ert 14
错误消息的含义是您不能将列表写入文件,只能写入"字符缓冲区对象",这意味着字符串或其他类似字符串的行为.
如果您只想以与打印到控制台相同的方式将列表写入文件,则可以编写str(thefile)或repr(thefile)(甚至使用重定向语法print而不是使用file.write).
但是你正在使用csv模块来读取输入,并且可能想要输出相同的格式,所以你可能也想用csv它来编写它.
你是这样读的:
list(csv.reader(open(filename, 'rb'), delimiter=',', quotechar='"'))[1:]
Run Code Online (Sandbox Code Playgroud)
所以这样写:
csv.writer(open('foo.csv', 'wb'), delimiter=',', quotechar='"').writerows(thefile)
Run Code Online (Sandbox Code Playgroud)
我应该提一下,我不会首先构建这样的代码; 我会做这样的事情:
with open('input.csv', 'rb') as infile, open('output.csv', 'wb') as outfile:
incsv = csv.reader(infile, delimiter=',', quotechar='"')
outcsv = csv.writer(outfile, delimiter=',', quotechar='"')
incsv.read() # skip first line
for line in incsv:
if line[3] != '':
outcsv.write(ProcessLine(line))
Run Code Online (Sandbox Code Playgroud)