0

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.

3
  • Iterate through the list and print it? Commented Aug 17, 2016 at 7:01
  • 4
    Possible duplicate of Writing a list to a file with Python Commented Aug 17, 2016 at 7:08
  • Please share your code, input and output. Commented Aug 17, 2016 at 7:46

2 Answers 2

1

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))) 
Sign up to request clarification or add additional context in comments.

Comments

0

files have a writelines method. use that instead of write

3 Comments

Hi John; your answer might be correct, but it would be better with some context; for example, you could explain how and why this proposed change would resolve the questioner's problem, perhaps with an illustration of the different output from the write and writelines methods, and perhaps including links to the relevant documentation. That would make it more useful to them, and also more useful to other site readers who are looking for solutions to similar problems.
@VinceBowdren, the question is supposed to include a minimal example code showing the problem. That would normally provide the context for (and be included in) my answer. Why do you not try to get the asker to improve the question as well so I can make the answer more specific?
@JohnLaRooy Your answer came up automatically in the review code, having been flagged as possibly low-value because of its length and content. The review queue had not asked me to review the question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.