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

kra*_*mir 45 python file python-3.x

我想将文件中的数字读入二维数组.

文件内容:

  • 包含w,h的行
  • h行包含用空格分隔的w整数

例如:

4 3
1 2 3 4
2 3 4 5
6 7 8 9
Run Code Online (Sandbox Code Playgroud)

zee*_*kay 73

假设你没有无关的空白:

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()])
Run Code Online (Sandbox Code Playgroud)

您可以将最后一个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]
Run Code Online (Sandbox Code Playgroud)

  • 是不是存储为字符串的值? (3认同)
  • +1:这是一个很好的答案,你熟练使用'readline`和`line in f`赢得了我的最高荣誉.干杯. (2认同)
  • @ Jean-ClaudeArbaut不,你是对的.在Python 3中,你可以自由地混合使用`next(f)`和`f.readline()`,因为`next()`实际上是使用`readline()`实现的,并且缓冲被移动到一个单独的类中使用从文件中读取的所有机制.感谢您指出了这一点.我现在记得几年前读过这篇文章了,但是当我写上一篇评论时,我已经忘记了. (2认同)

mac*_*ing 14

对我来说,这种看似简单的问题就是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:]]
Run Code Online (Sandbox Code Playgroud)

在这里查找生成器表达式.它们可以真正将代码简化为独立的功能单元!想象一下,用C++中的4行做同样的事情......这将是一个怪物.特别是列表生成器,当我是C++的时候,我总是希望我有类似的东西,而且我经常最终会构建自定义函数来构建我想要的各种数组.

  • 在 OP 提到的微不足道的情况下,C++ 版本虽然稍长一些,但不会像您所说的那样成为“怪物”。您将使用 fscanf() 或流和 vector<vector<int>>(甚至 int[][])。在读取和解析文件时,C++ 将提供对内存管理的更多控制。 (3认同)
  • 实际上,ifstreams 比 fscanf 更容易处理,fscanf 是一个 C 函数,而不是 C++ 函数。如果您只是在 C++ 中解析文本并且有任何比建议的 python 解决方案更复杂的东西,那么您显然做错了。 (2认同)

Art*_*nka 5

不知道你为什么需要 w,h。如果这些值实际上是必需的,并且意味着应该只读取指定数量的行和列,那么您可以尝试以下操作:

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)
Run Code Online (Sandbox Code Playgroud)