Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (47.6k points)
edited by

Is this the cleanest way to write a list to a file, since writelines() doesn't insert newline characters?

file.writelines(["%s\n" % item for item in list])

It seems like there would be a standard way.

closed

1 Answer

0 votes
by (106k points)
selected by
 
Best answer

For writing a list to a file with Python you can use a loop:-

with open('your_file.txt', 'w') as f:

          for item in my_list:

               f.write("%s\n" % item)

If you are using Python 2, you can also use the following piece of code:-

with open('your_file.txt', 'w') as f:

          for item in my_list:

                 print

Related questions

0 votes
1 answer
asked Jul 2, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.2k users

Browse Categories

...