Tôi cố gắng để viết một danh sách của một danh sách vào một tập tin mới, nhưng tôi nhận được lỗi này:Lỗi Loại: mong đợi một đối tượng nhân vật đệm
Traceback (most recent call last): File "", line 1, in dowork() File "C:\Python27\work\accounting\formatting quickbooks file\sdf.py", line 11, in dowork WriteFile() File "C:\Python27\work\accounting\formatting quickbooks file\sdf.py", line 71, in WriteFile f.write(thefile) TypeError: expected a character buffer object
Làm thế nào để viết một danh sách của một danh sách công việc một tập tin?
Đây là cách tôi đang viết:
def WriteFile():
global thefile
f = open("output"+'.csv','w')
f.seek(0)
f.write(thefile)
f.close()
và đây là nguồn gốc hoàn toàn nếu bạn cần nó:
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)))
Bạn thực sự nên thay thế biến toàn cầu bằng biến mà bạn chuyển đến từng chức năng và đóng các tệp khi bạn hoàn tất. Và bây giờ chúng ta có thể thấy toàn bộ mã, tôi khuyên bạn nên tổ chức lại nó để bạn có một hàm 'ProcessLine' (bạn có thể đảo ngược vòng lặp' line' và 'company'), và chỉ lọc từng dòng một, vì vậy bạn không cần danh sách và không cần xóa mọi thứ khỏi danh sách tại chỗ, v.v. Toàn bộ điều sẽ đơn giản hơn nhiều theo cách đó. – abarnert
có thể trùng lặp của [TypeError: dự kiến một đối tượng đệm ký tự - trong khi cố gắng lưu số nguyên vào textfile] (http: // stackoverflow.com/questions/9786941/typeerror-expected-a-character-buffer-object-while-trying-to-save-integer-to) –