开发者

problem with python list

开发者 https://www.devze.com 2023-02-19 09:21 出处:网络
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 ???

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 se开发者_如何学编程cond last line with the declaration of the list


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


Why not UserInputList += line.split()?


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号