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.
- Iterate through the list and print it?Shubham– Shubham2016-08-17 07:01:14 +00:00Commented Aug 17, 2016 at 7:01
- 4Possible duplicate of Writing a list to a file with PythonShubham– Shubham2016-08-17 07:08:28 +00:00Commented Aug 17, 2016 at 7:08
- Please share your code, input and output.barak manos– barak manos2016-08-17 07:46:44 +00:00Commented Aug 17, 2016 at 7:46
Add a comment |
2 Answers
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))) Comments
files have a writelines method. use that instead of write
3 Comments
Vince Bowdren
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.
John La Rooy
@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?
Vince Bowdren
@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.