10

list consists of RANDOM strings inside it

#example
list = [1,2,3,4]

filename = ('output.txt')
outfile = open(filename, 'w')
outfile.writelines(list)
outfile.close()

my result in the file

1234

so now how do I make the program produce the result that I want which is:

1
2
3
4
1
  • What are these indentation for? list does not contain any string at all Commented Dec 2, 2013 at 18:10

2 Answers 2

22
myList = [1,2,3,4]

with open('path/to/output', 'w') as outfile:
  outfile.write('\n'.join(str(i) for i in myList))

By the way, the list that you have in your post contains ints, not strings.
Also, please NEVER name your variables list or dict or any other type for that matter

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

1 Comment

names like list_ and dict_ are fine though
2

writelines() needs a list of strings with line separators appended to them but your code is only giving it a list of integers. To make it work you'd need to use something like this:

some_list = [1,2,3,4]

filename = 'output.txt'
outfile = open(filename, 'w')
outfile.writelines([str(i)+'\n' for i in some_list])
outfile.close()

In Python file objects are context managers which means they can be used with a with statement so you could do the same thing a little more succinctly with the following which will close the file automatically. It also uses a generator expression (enclosed in parentheses instead of brackets) to do the string conversion since doing that avoids the need to build a temporary list just to pass to the function.

with open(filename, 'w') as outfile:
    outfile.writelines((str(i)+'\n' for i in some_list))

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.