文件读写

2024-10-06 11:23:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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”。如何修复它的帮助?你知道吗


Tags: csvthein目的路由错误codeopen
2条回答

这就是你得到的TypeError。写入文件时,“students”类型应为字符串。使用str(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。例如:

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

相关问题 更多 >