how to write elements of a list to a text file python code example
Example 1: how to put a text file into a list python
# name.txt
david
mary
john
with open('names.txt', 'r') as f:
myNames = [line.strip() for line in f]
# Result
['david','mary','john']
Example 2: how to write lists to text file python
# define list of places
places = ['Berlin', 'Cape Town', 'Sydney', 'Moscow']
with open('listfile.txt', 'w') as filehandle:
for listitem in places:
filehandle.write('%s\n' % listitem)