user2958069
user2958069

Reputation: 93

writing a list to a txt file in python

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

Upvotes: 8

Views: 18852

Answers (2)

martineau
martineau

Reputation: 123393

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

Upvotes: 2

inspectorG4dget
inspectorG4dget

Reputation: 113905

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

Upvotes: 19

Related Questions