我有一个file
看起来像下面这样
file= '/user/home/file.txt'
file
[SKY]
/user/home/repo/study
[EARTH]
/user/home/learn/objects
[LOCAL]
/user/home/teach/files
[SAMP]
VKP
RNP
SAS
[TYPE]
HGH
[SAMP_ID]
VKP_TP_MA
RNP_TP_NA
SAS_SAS
[ENV]
....
现在我需要将项目从[SAMP]
和[SAMP_ID]
转移到一个列表中。
这就是我正在做的,就是给予我所需要的。但任何更好或优雅的解决方案都会很好
所以我的列表是samp
和samp_id
,这是我目前正在使用的解决方案
samp = []
samp_id = []
sampSection = False
samp_idection = False
for line in open(file, 'r'):
if len(line.strip()) == 0:
sampSection = False
continue
if line.strip() == '[SAMP]':
sampSection = True
continue
elif line.startswith('['):
sampSection = False
continue
if sampSection:
samp.append(line.strip())
continue
for line in open(file, 'r'):
if len(line.strip()) == 0:
samp_idection = False
continue
if line.strip() == '[SAMP_ID]':
samp_idection = True
continue
elif line.startswith('['):
samp_idection = False
continue
if samp_idection:
samp_id.append(line.strip())
continue
和samp
和samp_id
如下所示
samp =['VKP','RNP', 'SAS']
samp_id=['VKP_TP_MA','RNP_TP_NA', 'SAS_SAS']
在这种情况下,如果有更简单的解决方案,那就太好了
我将使用dict解析整个文件,而无需打开并重复文件两次:
如果您确实不想保留任何其他标签:
相关问题 更多 >
编程相关推荐