python – 将列表转换为字符串

我从一个文件中提取了一些数据,并希望将其写入第二个文件。但我的程序返回错误:

sequence item 1: expected string, list found

这似乎发生了,因为write()想要一个字符串,但它正在接收一个列表。

所以,对于这段代码,我如何将列表缓冲区转换为字符串,以便我可以将缓冲区的内容保存到file2?

file = open('file1.txt','r')
file2 = open('file2.txt','w')
buffer = []
rec = file.readlines()
for line in rec :
    field = line.split()
    term1 = field[0]
    buffer.append(term1)
    term2 = field[1]
    buffer.append[term2]
    file2.write(buffer)  # <== error
file.close()
file2.close()
尝试 str.join

file2.write(' '.join(buffer))

文档说:

Return a string which is the concatenation of the strings in the iterable iterable. The separator between elements is the string providing this method.

相关文章
相关标签/搜索