2010-05-25 32 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