try:
studfile = open("students.csv","r")
except IOError:
studfile = open("students.csv","w")
#later in the code
studfile.write(students)这个try / out块的目的是尝试并路由出IOError,但是我最终得到了另一条错误消息,它是“预期的字符缓冲区对象”。帮我解决这个问题?
发布于 2014-12-13 07:24:19
这就是你要得到的TypeError。您的“学生”类型应该是字符串,同时写入文件。使用str(students)可以解决您的问题。
编辑:str可以将任何对象转换为string类型。考虑到下面的评论:因为您没有提到student的类型。如果是字符串列表(假设)。那么你就不能这样写:studfile.write(students)。
您应该这样做:
for entry in students:
studfile.write(entry) # decide whether to add newline character or not发布于 2014-12-13 08:00:43
假设students是您希望保存为csv文件的某种形式的数据,那么最好使用csv文件IO中构建的python。例如:
import csv
with open("students.csv","wb") as studfile: # using with is good practice
...
csv_writer = csv.writer(studfile)
csv_writer.writerow(students) # assuming students is a list of datahttps://stackoverflow.com/questions/27456517
复制相似问题