4
>>> 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
Li-aung Yip
  • 12,320
  • 5
  • 34
  • 49
  • 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 Apr 11 '12 at 06:20

4 Answers4

7

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.

RanRag
  • 48,359
  • 38
  • 114
  • 167
3

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)
jamylak
  • 128,818
  • 30
  • 231
  • 230
  • 1
    If you want to join unicode strings, then you use the join method of a unicode string, so simply: `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.) – Karl Knechtel Apr 11 '12 at 06:22
0

You need to use join to join the list into a string. Change the write from

q.write(w)

to

q.write(''.join(w))
Abhijit
  • 62,056
  • 18
  • 131
  • 204
0

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.

Community
  • 1
  • 1
vaisakh
  • 1,041
  • 9
  • 19