0

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.

3
  • 2
    What have you tried? Even if your attempt is just reading lines from the file, that's a great place to start. Commented Mar 13, 2013 at 16:12
  • I literally just have inputFile= open(fileName, 'r') and I really don't have an idea where to go from there. Commented Mar 13, 2013 at 16:14
  • Well, any answer is going to involve iterating over lines in a file. Why not do a search to figure out how to get the lines? After you've gotten the lines, then you can start working on how to transform them into the lists you want. Commented Mar 13, 2013 at 16:23

3 Answers 3

2

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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())

Comments

0

You can also use the readLines

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.