尝试在Python中写入文件时接收TypeError

时间:2011-04-13 15:31:43

标签: python file-io typeerror

当我运行此代码时:

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:期望一个字符缓冲区对象

有什么想法吗?

1 个答案:

答案 0 :(得分:18)

findall(),因为名称表示返回Python 列表而不是字符串/缓冲区。

你不能写一个列表到文件句柄 - 它应该如何工作?

你期待什么?

file.write(str(tickers))

表示列表的字符串表示?

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

是否以逗号分隔的列表项串联?

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

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

file()是一种内置方法。