pikkip
pikkip

Reputation: 7

How to convert a list in Python to a text file?

I tried it but it comes in the form of a list in the file. I want it in a format without the brackets and the commas.

Upvotes: 0

Views: 1869

Answers (2)

Israel Unterman
Israel Unterman

Reputation: 13510

Let's start by the long way, to make it clear:

for item in mylist:
    f.write(str(item) + " ")

The above code will write your items (not necessarily strings, that's why the str() is applied) separated by spaces.

You can achieve the same thing without a loop, using the string's join() method, which takes a list of strings and joins them using the spaces, like this:

f.write(' '.join(map(str, mylist)))

Upvotes: 1

John La Rooy
John La Rooy

Reputation: 304205

files have a writelines method. use that instead of write

Upvotes: 0

Related Questions