【问题标题】:TypeError: expected a character buffer object when doing open()TypeError:在执行 open() 时需要一个字符缓冲区对象
【发布时间】:2012-04-21 02:49:35
【问题描述】:

所以我正在学习 Python。我正在用数组和 open() 做一件简单的事情,有时这段代码可以工作,有时却不行!请帮忙!

    print('Load? (Y/N)')
load = raw_input()
if load == "y":
    fin = open("myArr.bat", "r")
    myArr = fin.readline()
if load == "n":
    myArr = [0, 0, 0,
             0, 0, 0,
             0, 0, 0]
if load != "y" and load != "n":
    print 'WUT?'
    exit()

print (myArr[0]) ,  '|' ,  (myArr[1]) ,  '|' ,  (myArr [2])
print '----------'
print (myArr[3]) ,  '|' ,  (myArr[4]) ,  '|' ,  (myArr [5])
print '----------'
print (myArr[6]) ,  '|' ,  (myArr[7]) ,  '|' ,  (myArr [8])
print '_______________________________________________'
print 'What shall I change?'
print 'Number in array: '
foo = raw_input()
doo = int(float(foo))
print 'Number to change to: '
bar = raw_input()
dar = int(float(bar))
myArr[doo] = dar
print '_______________________________________________'
print (myArr[0]) ,  '|' ,  (myArr[1]) ,  '|' ,  (myArr [2])
print '----------'
print (myArr[3]) ,  '|' ,  (myArr[4]) ,  '|' ,  (myArr [5])
print '----------'
print (myArr[6]) ,  '|' ,  (myArr[7]) ,  '|' ,  (myArr [8])
fout = open("myArr.bat", "w")
fout.write(myArr)
fout.close()

它给了我这个:

   Traceback (most recent call last):
  File "Screen.py", line 35, in <module>
    fout.write(myArr)
TypeError: expected a character buffer object

请帮忙!

【问题讨论】:

    标签: python compiler-errors


    【解决方案1】:

    那是因为write 方法需要一个字符串作为第一个参数,但您传递给它的是一个数组。

    【讨论】:

    • 那么我如何作为字符串传递,然后我将如何检索它?求你的帮助!
    • @PlazmotechBinary,如果你想将数组中的序列化数据存储在一个文件中,然后读取文件并反序列化它,请使用pickle
    【解决方案2】:

    我猜你在测试代码并输入'n' 时会出现此错误,但是当你输入'y' 时,它工作得很好。这是因为以下几行:

    if load == "n":
    myArr = [0, 0, 0,
             0, 0, 0,
             0, 0, 0]
    

    这使得myArr 成为list。不只是将列表写入文件。您必须先将其转换为字符串(只能将字符串写入文件)。

    因此,根据您希望如何将此列表存储在文件中,您可以这样做:

    fout = open("myArr.bat", "w")
    fout.write(' '.join(map(str, myArr)))
    fout.close()
    

    这实际上会将以下行写入myArr.bat(假设myArr = [0, 0, 0, 0, 0, 0, 0, 0, 0]):

    0 0 0 0 0 0 0 0 0
    

    希望对你有帮助

    【讨论】:

    • 嗯...好吧,我将如何检索它?我能想到的唯一方法是:fin = open("myArr.bat", "r") myArr[0] = fin.readline(1) 但这行不通……因为你有这些空间。但是如果我删除空格,那么你会遇到 2 位数字的问题......我该怎么做?
    • myArr = map(int, open("myArr.bat").readline().strip().split())open中不指定"r",则默认使用"r"
    • 谢谢!这非常有帮助!
    猜你喜欢
    • 1970-01-01
    • 2013-06-29
    • 2012-09-17
    • 1970-01-01
    • 2019-06-22
    • 2021-10-15
    • 2017-04-18
    相关资源
    最近更新 更多