如何在Python中从文件读取数字?

72 投票
6 回答
384642 浏览
提问于 2025-04-16 20:52

我想把文件里的数字读进一个二维数组里。

文件内容格式如下:

  • 第一行包含两个数字,分别是宽度(w)和高度(h)
  • 接下来的h行,每行包含w个用空格分开的整数

举个例子:

4 3
1 2 3 4
2 3 4 5
6 7 8 9

6 个回答

6

不太明白你为什么需要宽度和高度。如果这些值确实是必须的,并且意味着只需要读取指定数量的行和列,那么你可以试试下面的代码:

output = []
with open(r'c:\file.txt', 'r') as f:
    w, h  = map(int, f.readline().split())
    tmp = []
    for i, line in enumerate(f):
        if i == h:
            break
        tmp.append(map(int, line.split()[:w]))
    output.append(tmp)
19

对我来说,这种看似简单的问题正是Python的魅力所在。尤其是如果你之前用过像C++这样的语言,处理简单的文本解析可能会让人很头疼,你会特别欣赏Python能提供的功能性解决方案。我会用几个内置函数和一些生成器表达式来保持简单。

你需要用到 open(name, mode) 来打开文件,myfile.readlines() 来读取文件内容,mystring.split() 来分割字符串,还有 int(myval) 来转换数据类型。然后,你可能还想用几个生成器把这些东西以Python的方式组合起来。

# This opens a handle to your file, in 'r' read mode
file_handle = open('mynumbers.txt', 'r')
# Read in all the lines of your file into a list of lines
lines_list = file_handle.readlines()
# Extract dimensions from first line. Cast values to integers from strings.
cols, rows = (int(val) for val in lines_list[0].split())
# Do a double-nested list comprehension to get the rest of the data into your matrix
my_data = [[int(val) for val in line.split()] for line in lines_list[1:]]

你可以在这里了解生成器表达式。它们能让你的代码变得更简洁,像一个个独立的功能单元!想象一下在C++中做同样的事情需要4行代码……那简直是个怪物。尤其是列表生成器,当我还是C++程序员的时候,我总希望能有这样的东西,结果经常需要自己写函数来构建我想要的每种数组。

104

假设你没有多余的空格:

with open('file') as f:
    w, h = [int(x) for x in next(f).split()] # read first line
    array = []
    for line in f: # read rest of lines
        array.append([int(x) for x in line.split()])

你可以把最后的for循环简化成一个嵌套的列表推导式:

with open('file') as f:
    w, h = [int(x) for x in next(f).split()]
    array = [[int(x) for x in line.split()] for line in f]

撰写回答