2010-05-25 26 views
41

He extraído algunos datos de un archivo y quiero escribirlos en un segundo archivo. Pero mi programa está devolviendo el error:Convertir una lista en una cadena

sequence item 1: expected string, list found 

Esto parece estar ocurriendo porque write() quiere una cadena, pero que está recibiendo una lista.

Entonces, con respecto a este código, ¿cómo puedo convertir la lista buffer en una cadena para que pueda guardar el contenido de buffer en 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

con ese código publicado, debe obtener oth er errores, también. p.ej. at '' buffer.append [term2] '' ... – miku

+1

Parece que está agregando datos al "buffer" para cada línea, y luego escribiendo todo el buffer en el archivo sin borrarlo nunca. Esto dará como resultado que los datos de la primera línea estén en el archivo una vez por cada línea en el archivo, los datos del segundo una vez menos que eso, y así sucesivamente. Esto probablemente no es lo que quieres. – geoffspear

Respuesta

18
''.join(buffer) 
+2

sí, aunque el OP probablemente quiera un espacio o una coma como separador, supongo. –

+1

Gracias por tu comentario. En ese caso use ''' .join (buffer)' o '','. Join (buffer)' – blokeley

+0

lo siento, todavía dice que el buffer es list, y '' .join (buffer) espera string .. – PARIJAT

47

Trate str.join:

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

Documentación dice:

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

Si desea que cada elemento en 'buffer' se escriba en una línea separada en' file2', use: ''\ n'.join (buffer)' – DavidRR

+0

@miku: Esto no funciona con python3. – user2284570

+0

@ user2284570 También funciona en python3. – Dominik

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

Método 1:

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

Método 2:

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

Método 3:

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

Falta un '.' después de' '' 'y antes de' join'. – ToolmakerSteve

2
file2.write(str(buffer)) 

Explicación: str(anything) convertirá cualquier objeto pitón en la representación de cadena. Similar a la salida que obtienes si haces print(anything), pero como una cadena.

NOTA: Esto probablemente no es lo que quiere OP, ya que no tiene control sobre cómo se concatenan los elementos de buffer - se puso , entre cada uno - pero puede ser útil para otra persona.

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

dará " 'a', 'b', 'c'" como salida

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

De the official Python Programming FAQ para 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 
Cuestiones relacionadas