tinydancer9454
tinydancer9454

Reputation: 401

python creating a list from lines in a file

I need to create a list of strings for each line in a file.

Example:

This is my file.
These are examples.

would create: ['This', 'is', 'my', 'file'] ['These', 'are', 'examples']

I need to do this because I am trying to translate a file into a pig latin file.

Upvotes: 0

Views: 166

Answers (3)

Zokis
Zokis

Reputation: 390

You can also use the readLines

f = open('file.txt', 'r')
lines = [line.split(' ') for line in f.readlines()]

Upvotes: 0

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29093

Try this:

res = []
with open(filename, 'r') as f:
    for line in f:
         res.append(line.split())

OR:

map(str.split, open(filename, 'r'))

If you need to get rid of dots:

res = []
with open(filename, 'r') as f:
    for line in f:
         res.append(line.strip('.').split())

Upvotes: 1

Makoto
Makoto

Reputation: 106389

Split each line in the file along the space character and retrieve it as a list.

f = open('filename.txt', 'r')
li = [line.split() for line in f]

Upvotes: 2

Related Questions