简体   繁体   中英

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
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 int s, not strings.
Also, please NEVER name your variables list or dict or any other type for that matter

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM