This question already has an answer here:
-
Concatenate elements of a list [duplicate]
1 answer
I have extracted some data from a file and want to write it to a second file. But my program is returning the error:
sequence item 1: expected string, list found
This appears to be happening because write()
wants a string but it is receiving a list.
So, with respect to this code, how can I convert the list buffer
to a string so that I can save the contents of buffer
to 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()
Try str.join
:
file2.write(\' \'.join(buffer))
Documentation says:
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) )
Explanation:
str(anything)
will convert any python object into its string representation. Similar to the output you get if you do print(anything)
, but as a string.
NOTE: This probably isn\'t what OP wants, as it has no control on how the elements of buffer
are concatenated -- it will put ,
between each one -- but it may be useful to someone else.
buffer=[\'a\',\'b\',\'c\']
obj=str(buffer)
obj[1:len(obj)-1]
will give \"\'a\',\'b\',\'c\'\" as output
file2.write(\',\'.join(buffer))
# it handy if it used for output list
list = [1, 2, 3]
stringRepr = str(list)
# print(stringRepr)
# \'[1, 2, 3]\'
From the official Python Programming FAQ for 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
Method 1:
import functools
file2.write(functools.reduce((lambda x,y:x+y), buffer))
Method 2:
import functools, operator
file2.write(functools.reduce(operator.add, buffer))
Method 3:
file2.write(\'\'.join(buffer))