computergeek
computergeek

Reputation: 33

Convert a text file into a list

This is what my text file consists of:

"I like ice cream very much"

So far this is my code:

f = open('nums.txt', 'r')
list = []
data1 = readline()
print (data1)

This is the output: I like ice cream very much

I was wondering how I could get it so each word is separated e.g. ['I', 'like', 'ice', 'cream', 'very', 'much']

I am working in Python 3.3. Any ideas?

Upvotes: 3

Views: 119

Answers (2)

Régis B.
Régis B.

Reputation: 10618

Here is the corresponding one-liner:

print(open("nums.txt").read().split())

Upvotes: 0

unutbu
unutbu

Reputation: 880677

Use the str.split method:

print(data1.split())

>>> data1 = 'I like ice cream very much'
>>> data1.split()
['I', 'like', 'ice', 'cream', 'very', 'much']

Upvotes: 1

Related Questions