Python 将文件读入两个整数列表

问题描述 投票:0回答:4

我想读取一个文件并提取两个双打列表 例如,file.txt 包含以下内容:

123 345 456 8919
231 521 363 1716

由空格 ' ' 分隔。我有以下代码来读取上面的文件:

    with open("file.txt") as f:
        for line in f.readline():
            cipher_array.append(line.split()[0])
            cipher_array.append(line.split()[1])
            halfmask.append(line.split()[2]) 
            halfmask.append(line.split()[3]) 

我收到以下错误:

 cipher_array.append(line.split()[1])
IndexError: list index out of range

我想让 cipher_array 由 [123, 345, 231, 521] 和 halfmask = [456, 8919, 363, 1716] 组成

我的代码有什么问题?提前致谢

python list loops readfile
4个回答
1
投票

也用

split(" ")
代替
split()
f.readline()
应该是
f.readlines()

cipher_array,halfmask=[],[]
with open("file.txt") as f:
    for line in f.readlines():
        cipher_array.append(float(line.split(" ")[0]))
        cipher_array.append(float(line.split(" ")[1]))
        halfmask.append(float(line.split(" ")[2]) )
        halfmask.append(float(line.split(" ")[3]))
cipher_array,halfmask


0
投票

您正在调用

f.readline()
,它将读取一行,然后对其进行迭代,因此您的
line
变量是单个字符。你的意思可能是
readlines
而不是
readline
。不过,最好直接遍历文件对象:

for line in f:

您还需要

strip()
行的尾随空格,然后将
split
的结果转换为
int
float
.


0
投票

你像

f.readline()
一样在单行上迭代,这将返回一行,看看try:

with open("file.txt", "r") as f:
  print(f.readline()) # will return 123 345 456 8919

因此,您可以按如下方式遍历文件:

numbers = []
with open("file.txt", "r") as f:
  for line in f:
    numbers.extend(line.split())
numbers = list(map(int, numbers))
numbers

0
投票

代码的问题是

f.readline()
只读取文件的第一行,所以循环只执行一次。将其替换为
f.readlines()
。 (注意最后的s)

© www.soinside.com 2019 - 2024. All rights reserved.