Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, add items from txt file into a list

Tags:

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] 
like image 333
kidkd Avatar asked Jun 29 '10 15:06

kidkd


People also ask

How do you import a text file into a list in Python?

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 do I turn a line into a list in Python?

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.


1 Answers

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] 
like image 104
Felix Kling Avatar answered Oct 31 '22 07:10

Felix Kling