Trey
Trey

Reputation: 73

How to add items from a text file into a list?

I've already tried:

with open('names.txt', 'r') as f:
    myNames = f.readlines() 

And multiple other ways that I have found on stack overflow but they are not doing exactly what I need.

I have a text file that has one line with multiple words ex: FLY JUMP RUN

I need these in a list but for them to be separate elements in the list like:

['FLY', 'JUMP', 'RUN']

Except when using the the methods I find on stack overflow, I get: ['FLY JUMP RUN']

But I need them to be separate because I am using the random.choice method on the list.

Upvotes: 0

Views: 86

Answers (2)

kmario23
kmario23

Reputation: 61505

@Trey: To answer your comment.

No. readlines() will read all the contents of the file into a single list while read() simply reads it as a single strring.

Try this code:

with open('names.txt', 'r') as f:
    myNames = f.read().split() #split by space

This will work as you expected for any type of data, as long as the words in a line is space separated.

Upvotes: 0

James Hurford
James Hurford

Reputation: 2058

As was mentioned in the comments, you should try

myNames = None
with open('names.txt', 'r') as f:
    myNames = f.read().split()

Assuming the file is written the way you say. Of course it won't matter as the default behaviour of split() is to split the string, using whitespace characters like spaces, and newline characters, so if your file consists of

One Two
Three

then

f.read().split()

will still return

["One", "Two", "Three"]

Upvotes: 1

Related Questions