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]
To read a file into a list in Python, use the file. read() function to return the entire content of the file as a string and then use the str. split() function to split a text file into a list. To read a file in Python, use the file.
How to Convert a String to a List of Words. Another way to convert a string to a list is by using the split() Python method. The split() method splits a string into a list, where each list item is each word that makes up the string. Each word will be an individual list item.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With