2010-05-25 37 views
41

Bir dosyadan bazı verileri aldım ve ikinci bir dosyaya yazmak istiyorum. Ama benim program hata veriyor:Listeyi bir dizeye dönüştürme

sequence item 1: expected string, list found 

Bu write() bir dize istediği için oluyor gibi görünüyor ama bir liste alıyor.

Bu nedenle, bu kodla ilgili olarak buffer listesini buffer içeriğini file2'a kaydedebilmem için bir dizeye nasıl dönüştürebilirim?

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

bu kodla birlikte gönderilir. Hatalar da var. Örneğin. '' buffer.append [term2] '' ... – miku

+1

Her satır için "arabellek" dosyasına veri ekliyorsunuz ve daha sonra tüm arabelleği dosyaya herhangi bir açıklama yapmadan yazıyorsunuz. Bu, dosyadaki her satır için dosyadaki birinci satırın verileriyle, ikinci verilerin verileri bundan daha az bir süre ile sonuçlanacak ve bu şekilde devam edecektir. Muhtemelen istediğin bu değil. – geoffspear

cevap

18
''.join(buffer) 
+2

Evet, her ne kadar OP muhtemelen bir boşluk veya virgül ayırıcı olarak istiyorsa da tahmin ediyorum. –

+1

Yorumlarınız için teşekkürler. Bu durumda '' '.join (buffer) 'veya'', '.' (Buffer) ' – blokeley

+0

'un birleşiminden faydalanırız, yine de tamponun bir liste olduğunu ve' '.join (buffer) dizgesini beklediğini söyler .. – PARIJAT

47

str.join deneyin:

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

Belgeleme diyor ki:

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

'buffer2'deki her öğenin' file2' içinde ayrı bir satıra yazılmasını istiyorsanız, şunu kullanın: '\ n'.join (buffer)' – DavidRR

+0

@miku: Bu python3 ile çalışmaz. – user2284570

+0

@ user2284570 Python3'te de çalışıyor. – Dominik

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

Yöntem 1:

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

Yöntem 2:

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

Yöntem 3:

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

'' 'sonra' '' ve 'join''den önce eksiksiniz. – ToolmakerSteve

2
file2.write(str(buffer)) 

Açıklama: str(anything) dize gösterimine herhangi piton nesne dönüştürür. print(anything) yaparsanız elde ettiğiniz çıktıya benzer, ancak bir dize olarak.

NOT: Bu, muhtemelen buffer öğelerinin birleştirilmesiyle ilgili herhangi bir kontrole sahip olmadığı için OP'nin istediği şey değil - her biri arasında , koyacaktır - ancak başkalarına yararlı olabilir.

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

olarak " 'a', 'b', 'c'" verecektir:

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 
İlgili konular