Converting a list to a string
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.
''.join(buffer)
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.
上一篇: 加入换行符
下一篇: 将列表转换为字符串