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()
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
When you convert a list into a set, all the duplicates will be removed. The set can then be converted back into a list with list() . The drawback of this method is that the use of set() also changes the original list order, which is not restored after it is converted back into a list.
We can use StringBuilder class to convert List to String. StringBuilder is the best approach if you have other than String Array, List. We can add elements in the object of StringBuilder using the append() method while looping and then convert it into string using toString() method of String class at the end.
Use the join() Method to Convert the List Into a Single String in Python. The join() method returns a string in which the string separator joins the sequence of elements. It takes iterable data as an argument. We call the join() method from the separator and pass a list of strings as a parameter.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With