我有一个看起来像的文件:
# Grace project file
#
@version 50005
@page size 600, 600
@default linewidth 2.5
@default linestyle 1
@default color 1
@default font 0
@default char size 1.2
@default symbol size 1.2
@g0 on
@target G0.S0
@type xy
-0.108851E+02 0.127435E-03
-0.108715E+02 0.127829E-03
-0.108579E+02 0.128191E-03
-0.108443E+02 0.128502E-03
-0.108306E+02 0.128726E-03
-0.108170E+02 0.128838E-03
-0.108034E+02 0.128751E-03
&
@target G0.S1
@type xy
-0.108851E+02 0.472694E-04
-0.108715E+02 0.474233E-04
-0.108579E+02 0.475837E-04
-0.108443E+02 0.477448E-04
-0.108306E+02 0.479052E-04
-0.108170E+02 0.480669E-04
-0.108034E+02 0.482279E-04
&
我试图从@target
行读取:
with open(filename, "r") as f:
q = 0
for key,group in it.groupby(f,lambda line: line.startswith('@target')):
x=[];y=[]
if not key:
group = list(group)
group.pop(0)
group.pop(-1)
# print(len(group))
for i in range(len(group)):
x.append(group[i].split()[0])
y.append(group[i].split()[1])
filen[q]=np.array(list(map(list,zip(x,y))),dtype=float)
问题是,它仍然在比赛前读取线条并给出错误:
Traceback (most recent call last):
File "/home/rudra/splitagr.py", line 47, in <module>
filen[q]=np.array(list(map(list,zip(x,y))),dtype=float)
ValueError: could not convert string to float: '@page'
我认为groupby
会在line.startswith(@target)
之后开始匹配,但后来@page
将如何发布,我不知道。如果我在@target
行之前手动删除所有内容,则可以正常工作。
请帮助
答案 0 :(得分:0)
您可以使用以下内容将文件缩小到仅@target
之后的那些行:
pos = 0
with open('filename', 'r') as f:
lines = f.readlines()
for idx, line in enumerate(lines):
if '@target' in line:
pos = idx + 1
break
lines = lines[pos:]
或更简单:
with open('filename', 'r') as f:
for line in f:
if '@target' not in line:
continue
# Found '@target' rest of logic.
希望有所帮助!