>>> w
['Parts-of-speech', 'disambiguation', 'techniques', '(', 'taggers', ')',
'are', 'often', 'used', 'to', 'eliminate', '(', 'or', 'substantially',
'reduce', ')', 'the', 'parts-of-speech', 'ambiguitiy', 'prior', 'to',
'parsing.', 'The', 'taggers', 'are', 'all', 'local', 'in', 'the', 'sense',
'that', 'they', 'use', 'information', 'from', 'a', 'limited', 'context',
'in', 'deciding', 'which', 'tag', '(', 's', ')', 'to', 'choose', 'for',
'each', 'word.', 'As', 'is', 'well', 'known', ',', 'these', 'taggers',
'are', 'quite', 'successful', '.']
>>> q=open("D:\unieng.txt","w")
>>> q.write(w)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument 1 must be string or read-only character buffer, not list
-
What do you want the file to look like as a result? Do you want brackets on either end and quotes around each item and commas in between? Or do you want each item on a line by itself? Or just what?Karl Knechtel– Karl Knechtel2012-04-11 06:20:56 +00:00Commented Apr 11, 2012 at 6:20
4 Answers
Use writelines() method to write your content.
>>> f = open("test.txt",'w')
>>> mylist = ['a','b','c']
>>> f.writelines(mylist)
file.writelines(sequence)
Write a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings. There is no return value
Note: writelines() does not add line separators.
Comments
w is a list and the write method of the file object doesn't accept list as the error explains.
You can convert w to a string and write that like so:
' '.join(w) #Joins elements with spaces in between
Then you can call:
q.write(str)
1 Comment
u' '.join(w). (I assume 2.x since you need to ask this question; in 3.x, strings are normally unicode and you have to go out of your way to create bytes objects.)You need to use join to join the list into a string. Change the write from
q.write(w)
to
q.write(''.join(w))
Comments
Here are two similar posts in Stackoverflow:-
Writing a list to a file with Python
Python: Write a list of tuples to a file
You will get some more options and alternatives there.