Say I have an empty list myNames = []
How can I open a file with names on each line and read in each name into the list?
like
names.txt
dave
jeff
ted
myNames = [dave,jeff,ted]
Say I have an empty list myNames = []
How can I open a file with names on each line and read in each name into the list?
like
names.txt
dave
jeff
ted
myNames = [dave,jeff,ted]
Read the documentation:
with open('names.txt', 'r') as f:
myNames = f.readlines()
The others already provided answers how to get rid of the newline character.
Update:
Fred Larson provides a nice solution in his comment:
with open('names.txt', 'r') as f:
myNames = [line.strip() for line in f]
f = open('file.txt','r')
for line in f:
myNames.append(line.strip()) # We don't want newlines in our list, do we?
Names = []
for line in open('names.txt','r').readlines():
Names.append(line.strip())
strip() cut spaces in before and after string...