【发布时间】:2014-01-19 01:43:17
【问题描述】:
我需要在特定行之后读取一个文本文件,比如说第 100 行。该行有特定的数字,例如“255”。然后我想使用 for 循环读取接下来的 500 行。在这 500 行中,我有一些数字要提取。比如在P[3]位置。然后我需要将这些值传递到一个数组中。最后我应该有几套像下面这样。我使用以下代码来做到这一点。但我失败了。谁能帮帮我。
文件如下所示
Generated by trjconv : a bunch of waters t= 0.00000
500
1SOL OW 1 1.5040 2.7580 0.6820
2SOL OW 4 1.5210 0.9510 2.2050
500SOL OW 2998 1.5310 1.7952 2.1981
3.12736 3.12736 3.12736
Generated by trjconv : a bunch of waters t= 9000.00000
500
1SOL OW 1 1.5040 2.7580 0.6820
2SOL OW 4 1.5210 0.9510 2.2050
500SOL OW 2998 1.5310 1.7952 2.1981
3.10941 3.10941 3.10941
Generated by trjconv : a bunch of waters t= 0.00000
500
1SOL OW 1 1.5040 2.7580 0.6820
2SOL OW 4 1.5210 0.9510 2.2050
500SOL OW 2998 1.5310 1.7952 2.1981
3.12736 3.12736 3.12736
Generated by trjconv : a bunch of waters t= 9000.00000
500
1SOL OW 1 1.5040 2.7580 0.6820
2SOL OW 4 1.5210 0.9510 2.2050
500SOL OW 2998 1.5310 1.7952 2.1981
3.10941 3.10941 3.10941
我写的代码
F = open('Data.gro', 'r')
A = open('XYZ.txt', 'w')
XO = []
I = range(1,500)
for line in F:
P = line.split()
if P[0] == '256': # after i found this I want to read next five hundred lines.
for R in I:
P = line.split()
XO.append(P[3])
R +=1
# after the for loop I want write 'XO' in to file as set 01 then should go to next P[0] == '256'
文件名“XYZ.txt”中的结果应如下所示
Set 01
X = [1.32, 4.132, 2.23, .... upto 500]
Set 02
X = [4.232, 1.162, 3.73, .... upto 500]
【问题讨论】:
-
您不想在每个 500 次循环后将
XO重置回[]吗?
标签: python file python-2.7