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
1
  • 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? Commented Apr 11, 2012 at 6:20

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

1 Comment

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.)
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))

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.