2017-04-12 59 views
1

我想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是(我generaly大约有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 

我想在找到“IQ”后打印少量元素作为列表。

我的首选方法是通过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 lines in jinp

预期结果for _ in line

https://da.gd/v9ts结果是range(2500),但我不想硬编码的行号。

+1

您可以发布您的输出和所需的输出吗? –

+0

@ t.m.adam:added – BaRud

+0

'for _ in line'会打印100行,因为'len(line)'是100。如果你想在“智商”之后打印这些行,你可以把它们放在一个列表中,然后遍历它 –

回答

0

您的问题,为u重复使用相同的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")