如何在Python中从文件中读取数字?
我想把文件中的数字读入二维数组 文件内容:如何在Python中从文件中读取数字?,python,file,python-3.x,Python,File,Python 3.x,我想把文件中的数字读入二维数组 文件内容: 包含w,h的行 包含用空格分隔的w整数的h行 例如: 4 3 1 2 3 4 2 3 4 5 6 7 8 9 假设没有多余的空格: 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.app
- 包含w,h的行
- 包含用空格分隔的w整数的h行
4 3
1 2 3 4
2 3 4 5
6 7 8 9
假设没有多余的空格:
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]
对我来说,这类看似简单的问题就是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:]]
查找生成器表达式。它们真的可以将您的代码简化为离散的功能单元!想象在C++中用4行做同样的事情…那将是一个怪物。特别是列表生成器,当我是C++的时候,我总是希望我有这样的东西,我经常会结束自定义函数来构造我想要的每一种数组。 < p>不知道为什么你需要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)
正在使用python2(例如python2.7.10)和python3(例如python3.6.4) 另一种方式: 正在使用Python 2(例如Python 2.7.10)和Python 3(例如Python 3.6.4), 对于复杂矩阵,请参见下面的示例(仅将
int
更改为complex
)
我更新了代码,该方法适用于初始in.txt
文件中任意数量的矩阵和任意类型的矩阵(int
,complex
,float
)
这个程序产生矩阵乘法作为应用。正在使用python2,为了使用python3,请进行以下更改
print to print()
及
剧本:
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)
作为输入文件,我采用.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
为了简单起见,这里有一个程序,它从文件中读取整数并对其排序
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()
回信
就这么简单,希望这有帮助您是否被困在某个特定的地方?请看一看(这里我不是投反对票的人),但这里有一个如何逐行读取文件的示例,而不是数字。您的问题忽略了对文件内容和所需输出的清晰描述。@Miro获取行是一个步骤,而您需要使用类似split()的东西来操作字符串你说你是python新手,所以我想你想学点东西,但如果你只是在这里使用答案,你就不会学到很多东西。而且,这看起来像家庭作业。但是在C++中,按数字读取,U将字符串拆分成数字,所以我不知道StARTAREN在哪里存储的值不是字符串?我想这是一个好的解决方案,但是我总是犹豫着迭代和追加…在我看来,使用列表生成器通常更简洁、更容易阅读,您可以在单个操作中完成,也可以不使用流控制结构,如for
循环。我更喜欢列表理解,直到它们变成巨大的嵌套怪物。+1:这是一个很好的答案,你熟练地使用了f
中的readline
和行赢得了我最高的敬意。干杯。@Jean-ClaudeArbaut不,你说得对。在Python3中,您可以自由地混合使用next(f)
和f.readline()
,因为next()
实际上是使用readline()
实现的,缓冲被移动到一个单独的类中,所有读取文件的机制都使用这个类。谢谢你指出这一点。我现在还记得几年前读到过这篇文章,但在我写上一篇评论时,我忘记了它。我认为这是行不通的cols,rows=(int(val)表示'4\n'中的val)
不执行您想要的操作。与[int(val)for val in line]
相同,因为line
类似于'1 2 3 4\n'
@Jason:是的,很抱歉我的原始代码中有几个错误,但要点是正确的。以上已更正。我想这就是迭代开发的目的!:)在小事案例中,C++版本虽然稍长,但不会像你所说的那样是“怪物”。您可以使用fscanf()或streams和vector(甚至是int[])。在读取和解析文件时,C++将提供更多的内存管理控制。实际上,IFSF比FSCNF更简单,它是C函数,而不是C++函数。如果你只是在C++中解析文本,并且有比建议的Python解决方案更复杂的东西,那么你显然做了一些错误的事情。有趣的方法,包括头数据,我甚至没有想到。1为了完整性。。。但它有点长/难读:)Thanx)我创建了扩展解决方案,它逐行迭代,并为所有出现的w,h创建列表列表。但是,已经选择了最佳答案)
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()