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

时间:2011-07-05 13:40:25

标签: python file python-3.x

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

文件内容:

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

例如:

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

5 个答案:

答案 0 :(得分:71)

假设你没有无关的空白:

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]

答案 1 :(得分:13)

对我来说,这种看似简单的问题就是Python的全部内容。特别是如果你来自像C ++这样的语言,简单的文本解析可能会让你感到痛苦,你会非常感谢python可以提供的功能单元解决方案。我会用一些内置函数和一些生成器表达式来保持它非常简单。

您需要open(name, mode)myfile.readlines()mystring.split()int(myval),然后您可能需要使用几个生成器将它们放在一起一种pythonic方式。

# 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:]]

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

答案 2 :(得分:3)

不确定为什么你需要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)

答案 3 :(得分:0)

为了使答案简单,这里是一个程序,该程序从文件中读取整数并对它们进行排序

f = open("input.txt", 'r')

nums = f.readlines()
nums = [int(i) for i in nums]

读取文件的每一行后,将每个字符串转换为数字

nums.sort()

对数字进行排序

f.close()

f = open("input.txt", 'w')
for num in nums:
    f.write("%d\n" %num)

f.close()

将它们写回 如此简单,希望对您有所帮助

答案 4 :(得分:-2)

正在使用python2(例如Python 2.7.10)和python3(例如Python 3.6.4)

with open('in.txt') as f:
  rows,cols=np.fromfile(f, dtype=int, count=2, sep=" ")
  data = np.fromfile(f, dtype=int, count=cols*rows, sep=" ").reshape((rows,cols))
另一种方式: 正在使用python2(例如Python 2.7.10)和python3(例如Python 3.6.4), 以及复杂矩阵,请参阅下面的示例(仅将int更改为complex

with open('in.txt') as f:
   data = []
   cols,rows=list(map(int, f.readline().split()))
   for i in range(0, rows):
      data.append(list(map(int, f.readline().split()[:cols])))
print (data)

我更新了代码,此方法适用于初始int文件中的任意数量的矩阵和任何类型的矩阵(complexfloatin.txt

该程序产生矩阵乘法作为应用程序。正在使用python2,为了使用python3进行以下更改

print to print()

print "%7g" %a[i,j],    to     print ("%7g" %a[i,j],end="")

脚本:

import numpy as np

def printMatrix(a):
   print ("Matrix["+("%d" %a.shape[0])+"]["+("%d" %a.shape[1])+"]")
   rows = a.shape[0]
   cols = a.shape[1]
   for i in range(0,rows):
      for j in range(0,cols):
         print "%7g" %a[i,j],
      print
   print      

def readMatrixFile(FileName):
   rows,cols=np.fromfile(FileName, dtype=int, count=2, sep=" ")
   a = np.fromfile(FileName, dtype=float, count=rows*cols, sep=" ").reshape((rows,cols))
   return a

def readMatrixFileComplex(FileName):
   data = []
   rows,cols=list(map(int, FileName.readline().split()))
   for i in range(0, rows):
      data.append(list(map(complex, FileName.readline().split()[:cols])))
   a = np.array(data)
   return a

f = open('in.txt')
a=readMatrixFile(f)
printMatrix(a)
b=readMatrixFile(f)
printMatrix(b)
a1=readMatrixFile(f)
printMatrix(a1)
b1=readMatrixFile(f)
printMatrix(b1)
f.close()

print ("matrix multiplication")
c = np.dot(a,b)
printMatrix(c)
c1 = np.dot(a1,b1)
printMatrix(c1)

with open('complex_in.txt') as fid:
  a2=readMatrixFileComplex(fid)
  print(a2)
  b2=readMatrixFileComplex(fid)
  print(b2)

print ("complex matrix multiplication")
c2 = np.dot(a2,b2)
print(c2)
print ("real part of complex matrix")
printMatrix(c2.real)
print ("imaginary part of complex matrix")
printMatrix(c2.imag)

作为输入文件我采用in.txt

4 4
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
4 3
4.02 -3.0 4.0
-13.0 19.0 -7.0
3.0 -2.0 7.0
-1.0 1.0 -1.0
3 4
1 2 -2 0
-3 4 7 2
6 0 3 1
4 2
-1 3
0 9
1 -11
4 -5

complex_in.txt

3 4
1+1j 2+2j -2-2j 0+0j
-3-3j 4+4j 7+7j 2+2j
6+6j 0+0j 3+3j 1+1j
4 2
-1-1j 3+3j
0+0j 9+9j
1+1j -11-11j
4+4j -5-5j

,输出如下:

Matrix[4][4]
     1      1      1      1
     2      4      8     16
     3      9     27     81
     4     16     64    256

Matrix[4][3]
  4.02     -3      4
   -13     19     -7
     3     -2      7
    -1      1     -1

Matrix[3][4]
     1      2     -2      0
    -3      4      7      2
     6      0      3      1

Matrix[4][2]
    -1      3
     0      9
     1    -11
     4     -5

matrix multiplication
Matrix[4][3]
  -6.98      15       3
 -35.96      70      20
-104.94     189      57
-255.92     420      96

Matrix[3][2]
    -3     43
    18    -60
     1    -20

[[ 1.+1.j  2.+2.j -2.-2.j  0.+0.j]
 [-3.-3.j  4.+4.j  7.+7.j  2.+2.j]
 [ 6.+6.j  0.+0.j  3.+3.j  1.+1.j]]
[[ -1. -1.j   3. +3.j]
 [  0. +0.j   9. +9.j]
 [  1. +1.j -11.-11.j]
 [  4. +4.j  -5. -5.j]]
complex matrix multiplication
[[ 0.  -6.j  0. +86.j]
 [ 0. +36.j  0.-120.j]
 [ 0.  +2.j  0. -40.j]]
real part of complex matrix
Matrix[3][2]
      0       0
      0       0
      0       0

imaginary part of complex matrix
Matrix[3][2]
     -6      86
     36    -120
      2     -40