简体   繁体   English

将两行分开的文件内容读入列表

[英]Reading in file contents separated by two lines into a list

I have a text file containing: 我有一个包含以下内容的文本文件:

5
1 2 3 4 5

and I want to read in the contents into a list in python. 我想将内容读入python列表中。 The issue I'm facing is that i want to ignore the number 5 which is on the first line in the file. 我面临的问题是我想忽略文件第一行中的数字5。 The number 5 represents the number of elements below it which is 5. Instead, i want to only append 1,2,3,4,5 into a list. 数字5表示其下的元素数为5。相反,我只想将1,2,3,4,5附加到列表中。

[1,2,3,4,5]

I tried this: 我尝试了这个:

file = open('text.txt','r')
textfile = file
lst = []

for line in textfile:
    line = line.strip().split(',')
    line[1] = int(line[1])         #convert 1,2,3,4,5 into integers
    lst.append(line[1])
print(lst)

The error I'm getting is "index out of range". 我得到的错误是“索引超出范围”。

Add the line next(textfile) just before the loop. 在循环之前添加next(textfile)行。 It will discard the first line from the file. 它将丢弃文件的第一行。

Next, you are not converting the line to intereg numbers. 接下来,您不会将行转换为内部编号。 You only convert the second element, line[1] . 您只需转换第二个元素line[1] The right way to convert is: 正确的转换方法是:

lst = [int(i) for i in line.split()]

or 要么

lst = list(map(int, line.split()))

To summarize, your "perfect" program looks like this: 总而言之,您的“完美”程序如下所示:

with open('text.txt') as infile:
    next(infile)
    for line in infile:
        lst = [int(i) for i in line.split()]
        print(lst)

Just want to add a minor correction to @DyZ answer as If I understand correctly, you want list [1,2,3,4,5] not ['1,2,3,4,5'] 只是想对@DyZ答案添加一个较小的更正,因为如果我理解正确,那么您想列出[1,2,3,4,5]而不是['1,2,3,4,5']

with open('text.txt') as infile:
    next(infile)
    for line in infile:
        lst = [int(i) for i in line.split()]
        print(lst)

If you use line.split(',') with int it will result into ValueError - invalid literal for int() 如果将line.split(',')int ,则会导致ValueError - invalid literal for int()

The text file: 文本文件:

5
1 2 3 4 5
3 4 5 6 7

the code: 编码:

file = open('C:\\Users\\lenovo\\Desktop\\text.txt','r')

for line in file.readlines()[1:3]:
      lst=[int(i) for i in line.strip().split()]
      print(lst)

output: 输出:

[1, 2, 3, 4, 5]
[3, 4, 5, 6, 7]

I'm poor in English,can't explain it with English,hope you could understand( ^__^ ) 我英语不好,无法用英语解释,希望你能理解( ^ __ ^

You can try this approach : 您可以尝试以下方法:

with open('file','r') as f:
    for line_no,line in enumerate(f):
        if line_no%2==0:
            pass
        else:
            print([int(int_) for int_ in line if int_.strip()!=''])

output: 输出:

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM