2010-05-25 279 views
41

我已经从文件中提取了一些数据,并希望将其写入第二个文件。但我的程序返回错误:将列表转换为字符串

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() 
+3

与该代码张贴,你应该得到oth呃错误。例如在''buffer.append [term2]''... – miku 2010-05-25 15:41:49

+1

您似乎正在将数据添加到每行的“缓冲区”,然后将整个缓冲区写入文件而不清除它。这将导致第一行的数据在文件中的每一行都存在一次,第二行的数据少于一次,依此类推。这可能不是你想要的。 – geoffspear 2010-05-25 16:37:34

回答

18
''.join(buffer) 
+2

是的,虽然OP可能需要一个空格或逗号作为分隔符,我猜测。 – 2010-05-25 15:36:29

+1

感谢您的评论。在这种情况下使用'''.join(buffer)'或'','。join(buffer)' – blokeley 2010-05-25 15:45:44

+0

对不起,它仍然说缓冲区是列表,''.join(buffer)期望字符串.. – PARIJAT 2010-05-25 15:52:58

47

尝试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.

+0

如果你想把'buffer'中的每个项目写入'file2'中的一个单独的行,请使用:''\ n'.join(buffer)' – DavidRR 2015-01-20 17:01:13

+0

@miku:这不适用于python3。 – user2284570 2015-10-20 22:55:30

+0

@ user2284570它也可以在python3中工作。 – Dominik 2016-10-29 14:09:07

1
file2.write(','.join(buffer)) 
0

方法1:

import functools 
file2.write(functools.reduce((lambda x,y:x+y), buffer)) 

方法2:

import functools, operator 
file2.write(functools.reduce(operator.add, buffer)) 

方法3:

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

在''''之后和'join'之前缺少'.'。 – ToolmakerSteve 2016-01-27 20:24:41

2
file2.write(str(buffer)) 

说明: str(anything)将任何Python对象转换成它的字符串表示。类似于你输出的结果,如果你做print(anything),但是作为一个字符串。

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

0
buffer=['a','b','c'] 
obj=str(buffer) 
obj[1:len(obj)-1] 

会给 “ 'A', 'B', 'C'” 作为输出

-1
# it handy if it used for output list 
list = [1, 2, 3] 
stringRepr = str(list) 
# print(stringRepr) 
# '[1, 2, 3]' 
0

the official Python Programming FAQ用于Python 3.6.4:

What is the most efficient way to concatenate many strings together? str and bytes objects are immutable, therefore concatenating many strings together is inefficient as each concatenation creates a new object. In the general case, the total runtime cost is quadratic in the total string length.

To accumulate many str objects, the recommended idiom is to place them into a list and call str.join() at the end:

chunks = [] 
for s in my_strings: 
    chunks.append(s) 
result = ''.join(chunks) 

(another reasonably efficient idiom is to use io.StringIO)

To accumulate many bytes objects, the recommended idiom is to extend a bytearray object using in-place concatenation (the += operator):

result = bytearray() 
for b in my_bytes_objects: 
    result += b