将每行用空格分隔的数据赋值给变量
基本上,我想用Python来读取下面文件最后两行中的每一条数据,并把它们存到不同的变量里。
这个文件的格式如下:
a b c
10
10 0 0
2 5
xyz
10 12 13
11 12 12.4
1 34.5 10.8
我希望输出的结果是这样的:
d=11, e=12, f=12.4
g=1 h =34.5 i=10.8
如果我有大约100行(在xyz之后),每行有三条数据,我该如何循环读取这些行呢?而我只需要读取最后三行。
下面是我做的尝试,但似乎没有什么进展。
p1=open('aaa','r')
im=open('bbb','w')
t=open('test','w')
lines=p1.readlines()
i=0
for line in lines:
Nj=[]
Nk=[]
Cx=Cy=Cz=Nx=Ny=Nz=0
i=i+1
if line.strip():
if i==1:
t.write(line)
dummy=line.strip().split()
a1=dummy[0]
a2=dummy[1]
a3=dummy[2]
print("The atoms present are %s, %s and %s" %(a1, a2,a3))
if i==2:
t.write(line)
if i==3:
t.write(line)
if i==4:
t.write(line)
if i==5:
t.write(line)
if i==6:
t.write(line)
dummy=line.strip().split()
Na1=dummy[0]
Na2=dummy[1]
Na3=dummy[2]
import string
N1=string.atoi(Na1)
N2=string.atoi(Na2)
N3=string.atoi(Na3)
print("number of %s atoms= %d "%(a1,N1))
print("number of %s atoms= %d "%(a2,N2))
print("number of %s atoms= %d "%(a3,N3))
if i==7:
t.write(line)
if i==8:
t.write(line)
for i, line in enumerate(p1):
if i==8:
dummy=line.strip().split()
Njx=dummy[0]
Njy=dummy[1]
Njz=dummy[2]
import string
Njx=string.atof(Njx)
Njy=string.atof(Njy)
Njz=string.atof(Njz)
Nj = [Njx, Njy, Njz]
elif i==9:
dummy=line.strip().split()
Nkx=dummy[0]
Nky=dummy[1]
Nkz=dummy[2]
import string
Nkx=string.atof(Nkx)
Nky=string.atof(Nky)
Nkz=string.atof(Nkz)
Nk = [Nkx, Nky, Nkz]
break
2 个回答
0
给你来了
with open("text.txt", "r") as f:
# Get two last lines, remove the '\n'
contents = map(lambda s : s[:-1], f.readlines()[-2:])
# Get the three last lines,
[[d,e,f],[g,h,i]] = map(lambda s : map(float, s.split(" ")[-3:]), contents)
# Check the result
print (d,e,f,g,h,i)
解释:
with open("text.txt", "r") as f:
是在Python中处理文件的推荐方式,想知道为什么可以看看文件输入输出的教程。contents = map(lambda s : s[:-1], f.readlines()[-2:])
这行代码的意思是把文件f
的内容读进一个字符串列表里,使用readlines()
方法,然后取最后两行,使用[-2:]
,再通过lambda s : s[:-1]
去掉每行末尾多余的'\n'
。到这一步,我们的
contents
应该包含最后两行的内容。表达式
map(lambda s : map(float, s.split(" ")[-3:]), contents)
是把这两行内容按空格分开,然后整理成一个列表[[d,e,f],[g,h,i]]
。这里的[-3:]
是为了去掉前面的空格。
1
你可以用下面的代码读取文件的最后两行:
f = open(file, "r")
lines = f.readlines()[-2:] # change this if you want more than the last two lines
f.close()
split1 = lines[0].strip().split(' ') # In the example below: lines[0] = "4 5 6\n"
split2 = lines[1].strip().split(' ') # lines[1] = "7 8 9"
接着,你可以把这些值赋给你的变量:
d,e,f = [int(x) for x in split1]
g,h,i = [int(x) for x in split2]
这样做会把每一行的三个值分别赋给 d,e,f,g,h,i
,比如:
(你的文件)
...
1 2 3
4 5 6
7 8 9
(结果)
d = 4
e = 5
f = 6
g = 7
h = 8
i = 9