【问题标题】:Receiving TypeError while trying to write to file in Python尝试在 Python 中写入文件时收到 TypeError
【发布时间】:2011-08-04 20:08:26
【问题描述】:

当我运行这段代码时:

tickers = re.findall(r'Process Name: (\w+)', s)

file = open("C:\Documents and Settings\jppavan\My Documents\My Dropbox\Python Scripts\Processes\GoodProcesses.txt","w")
file.write(tickers)
file.close()

返回常见错误:

TypeError: 需要一个字符缓冲区对象

有什么想法吗?

【问题讨论】:

    标签: python file-io typeerror


    【解决方案1】:

    findall() 顾名思义,返回 Python list 而不是字符串/缓冲区。

    您不能将列表写入文件句柄 - 那应该如何工作?

    你期待什么?

    file.write(str(tickers))
    

    对于列表的字符串表示?

    或者

    file.write(', '.join(tickers))
    

    列表项的逗号分隔连接?

    无论如何...write(..) 需要一个字符串或一个缓冲区。

    除此之外:不要将文件句柄称为“文件”。

    file() 是一个内置方法。

    【讨论】:

    • 啊,有道理。我可以使用字符串表示或逗号分隔。这消除了错误,但没有任何输出到文件,即使它应该,所以我应该能够从这里弄清楚。
    • 另外,在命名文件文件时,我确实想过不这样做,但是是的......
    • 显然你的正则表达式不匹配。获取 pdb 并对其进行调试。
    猜你喜欢
    • 2021-08-26
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 2021-12-09
    • 1970-01-01
    相关资源
    最近更新 更多