2024-10-06 11:23:14 发布
网友
try: studfile = open("students.csv","r") except IOError: studfile = open("students.csv","w") #later in the code studfile.write(students)
这个try/except块的目的是尝试并路由出IOError,但我最终得到另一个错误消息,即“需要一个character buffer object”。如何修复它的帮助?你知道吗
这就是你得到的TypeError。写入文件时,“students”类型应为字符串。使用str(students)应该可以解决您的问题。你知道吗
TypeError
str(students)
编辑: str可以将任何对象转换为string类型。考虑到以下意见: 因为你没有提到student的类型。如果是字符串列表(假设)。你不能这样写:studfile.write(students)。你知道吗
str
string
student
studfile.write(students)
您应该执行类似的操作:
for entry in students: studfile.write(entry) # decide whether to add newline character or not
假设students是希望另存为csv文件的某种形式的数据,那么最好使用python内置的csv文件IO。例如:
students
csv
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 data
这就是你得到的
TypeError
。写入文件时,“students”类型应为字符串。使用str(students)
应该可以解决您的问题。你知道吗编辑:
str
可以将任何对象转换为string
类型。考虑到以下意见: 因为你没有提到student
的类型。如果是字符串列表(假设)。你不能这样写:studfile.write(students)
。你知道吗您应该执行类似的操作:
假设
students
是希望另存为csv
文件的某种形式的数据,那么最好使用python内置的csv文件IO。例如:相关问题 更多 >
编程相关推荐