将列表转换为字符串

2024-04-20 07:21:52 发布

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

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

sequence item 1: expected string, list found

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

那么,对于这段代码,如何将列表buffer转换为字符串,以便将buffer的内容保存为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()

Tags: 文件term1字符串txtfield列表bufferline
3条回答

尝试^{}

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.

file2.write( str(buffer) )

说明: str(anything)将把任何python对象转换为其字符串表示。类似于print(anything)的输出,但作为字符串。

注意:这可能不是OP想要的,因为它无法控制buffer元素是如何连接的——它将,放在每个元素之间——但它可能对其他人有用。

''.join(buffer)

相关问题 更多 >