62

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()
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
PARIJAT
  • 657
  • 1
  • 5
  • 4
  • 3
    with that code posted, you should get other errors, too. e.g. at ``buffer.append[term2]`` ... – miku May 25 '10 at 15:41
  • 1
    You appear to be adding data to the "buffer" for each line, and then writing the whole buffer to the file without ever clearing it. This will result in the first line's data being in the file once for every line in the file, the second's data one fewer time than that, and so on. This is probably not what you want. – Wooble May 25 '10 at 16:37

8 Answers8

71

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.

miku
  • 181,842
  • 47
  • 306
  • 310
27
''.join(buffer)
blokeley
  • 6,726
  • 9
  • 53
  • 75
  • 2
    yes, though the OP probably wants a space or comma as a separator I'm guessing. – Justin Peel May 25 '10 at 15:36
  • 1
    Thanks for comment. In which case use `' '.join(buffer)` or `','.join(buffer)` – blokeley May 25 '10 at 15:45
  • sorry it still says that buffer is list , and the ' '.join(buffer) expect string.. – PARIJAT May 25 '10 at 15:52
  • `str.join()` does not expect a string per se, it expects a _list_ of strings. The code you provided us, sans syntax errors, does exactly that. Maybe you should give us the actual code? – badp May 25 '10 at 16:36
  • @PARJAT, @bp, are you addressing the original poster or me? `buffer` is a list of strings and therefore `''.join(buffer)` will join them into one string. – blokeley May 26 '10 at 05:59
5
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.

ToolmakerSteve
  • 18,547
  • 14
  • 94
  • 196
5
buffer=['a','b','c']
obj=str(buffer)
obj[1:len(obj)-1]

will give "'a','b','c'" as output

Saurabh
  • 7,525
  • 4
  • 45
  • 46
3
file2.write(','.join(buffer))
Tendayi Mawushe
  • 25,562
  • 6
  • 51
  • 57
2

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))
Sylhare
  • 5,907
  • 8
  • 64
  • 80
Shandeep Murugasamy
  • 311
  • 2
  • 3
  • 15
1
# it handy if it used for output list
list = [1, 2, 3]
stringRepr = str(list)
# print(stringRepr)
# '[1, 2, 3]'
Lurking Elk
  • 163
  • 1
  • 4
1

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
chb
  • 1,727
  • 7
  • 25
  • 47