我在匹配后尝试readline
来自文件:
with open(jij, "a") as jout:
with open(jfile, "r") as jinp:
for line in jinp:
if line.strip().startswith("IQ"):
# for _ in line:
#for lines in jinp:
for lines in range(2500):
# lines = jinp.readline()
rows = jinp.readline().split()
print("{0:<3s}{1:<3s}{2:<3s}{3:<3s}{4:>3s}{5:>3s}{6:>3s}{7:>15s}{8:>7s}".
format(rows[3], rows[2], rows[0], rows[1], rows[4], rows[5], rows[6], rows[11], rows[10]))
非常短jfile
(我通常有大约1000行,但可能更大):
Isotropic exchange couplings Jij
number of sites NQ = 2
number of types NT = 2
site occupation:
1 1 1 1.000
2 1 2 1.000
IQ IT JQ JT N1 N2 N3 DRX DRY DRZ DR J_ij [mRy] J_ij [meV]
1 1 2 2 -1 -1 -1 -0.500 -0.500 -0.681 0.982 0.159317355 2.167623834
1 1 2 2 0 -1 -1 0.500 -0.500 -0.681 0.982 0.159317355 2.167623834
1 1 2 2 -1 0 -1 -0.500 0.500 -0.681 0.982 0.159317355 2.167623834
1 1 2 2 0 0 -1 0.500 0.500 -0.681 0.982 0.159317355 2.167623834
1 1 2 2 -1 -1 0 -0.500 -0.500 0.681 0.982 0.159317355 2.167623834
1 1 2 2 0 -1 0 0.500 -0.500 0.681 0.982 0.159317355 2.167623834
1 1 2 2 -1 0 0 -0.500 0.500 0.681 0.982 0.159317355 2.167623834
1 1 2 2 0 0 0 0.500 0.500 0.681 0.982 0.159317355 2.167623834
1 1 1 1 0 -1 0 0.000 -1.000 0.000 1.000 1.457569899 19.831256008
1 1 1 1 -1 0 0 -1.000 0.000 0.000 1.000 1.453728096 19.778985590
我试图在找到&#34; IQ&#34;。
后打印少量元素作为列表我首选的方法是for _ in line
执行此操作,该操作仅限前100行; for lines in jinp
正在跳过一行,然后阅读下一行。只有当我把它放在范围内时,它才能正常工作。但我不想要一个固定的行号。
for _ in line
出了什么问题?
https://da.gd/CtKZ是完整的文件。
https://da.gd/7V8F结果为for lines in range(2500)
https://da.gd/6cx3结果为for _ in line
https://da.gd/v9ts结果为for lines in jinp
预期结果来自range(2500)
,但我不想对行号进行硬编码。
答案 0 :(得分:0)
你的问题是你重复使用相同的fd:
rows = jinp.readline().split()# This make the pointer point to next line
你所有的解决方案都有这条线+另一种方式迭代:
# for _ in line: go over the chars in the line (100)
#for lines in jinp: go over the open file - > so you read twice per iteration
你可以使用它,更短,更可读。
flag = False
with open(jij, "a") as jout:
with open(jfile, "r") as jinp:
for line in jinp:
if flag:
rows = line.split()
jout.write("{0:<3s}{1:<3s}{2:<3s}{3:<3s}{4:>3s}{5:>3s}{6:>3s}{7:>15s}{8:>7s}\n".
format(rows[3], rows[2], rows[0], rows[1], rows[4], rows[5], rows[6], rows[11],
rows[10]))
else:
flag = line.strip().startswith("IQ")