基本上我想使用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之后),每行有三个数据,我怎么能循环。而且我只需要阅读其中的最后3行。
以下是我所做的,但似乎无法到达任何地方。
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
答案 0 :(得分: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
答案 1 :(得分: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中使用文件的推荐方法,请参阅文件I / O教程以了解原因。
contents = map(lambda s : s[:-1], f.readlines()[-2:])
这会使用f
将readlines()
的内容加载到字符串列表中,使用[-2:]
获取最后两个,并删除不必要的{{} 1}}通过映射'\n'
。
此时,我们的lambda s : s[:-1]
应包含最后两行。
表达式contents
将{2}中的每一行拆分为map(lambda s : map(float, s.split(" ")[-3:]), contents)
,然后将其解压缩到列表" "
。这里的[[d,e,f],[g,h,i]]
是删除前面的空格。