Reputation: 401
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
Reputation: 390
You can also use the readLines
f = open('file.txt', 'r')
lines = [line.split(' ') for line in f.readlines()]
Upvotes: 0
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
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