2

Hi im trying to create a list adding to it via a for loop reading line by line from a txt file. Im getting a syntax error on the list but am unsure about how to fix the problem ???

import re
file = open("text.txt","r")
text = file.readlines()
file.close()

line_count=0

for line in text:
    User_Input_list[] += [] + line.split()
    line_count += 1

the problem seems to be on the second last line with the declaration of the list

1
  • 3
    "declaration"? Python doesn't have declarations. What do you think is going on in that line? Please clarify your understanding. Commented Mar 23, 2011 at 13:53

3 Answers 3

7

Do it like this:

input = []
line_count = 0
with open("text.txt","r") as file:
    for line in file:
        input.extend(line.split())
        line_count += 1
Sign up to request clarification or add additional context in comments.

1 Comment

or you could use for line_count,line in enumerate(file,start=1): as a way of rolling the counter in the loop definition.
0

Why not UserInputList += line.split()?

1 Comment

This would create a nested list (which of course may or may not be what the OP wanted, the question is a bit unclear).
0

If you want each line in the file to be a separate element in the list, here's a simpler way to do it:

import re
file = open("text.txt","r")
text = file.readlines()
file.close()

line_count=0
line_list = []
for line in text:
    line_list.append(line)
    line_count += 1

Or using list comprehension:

import re
file = open("text.txt","r")
text = file.readlines()
file.close()

line_list = []
[line_list.append(a_line) for a_line in text]
line_count = len(line_list)

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.