使用输入文件中的信息根据条件生成列表的优雅方法

时间:2019-04-08 09:30:23

标签: python if-statement

我有一个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]转移到列表中。 这就是我正在做的,正在满足我的需求。但是,任何更好或优雅的解决方案都将很好。

所以我的列表是sampsamp_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

sampsamp_id如下所示,

samp =['VKP','RNP', 'SAS']
samp_id=['VKP_TP_MA','RNP_TP_NA', 'SAS_SAS']

在这种情况下,如果有任何更简单的解决方案,那就太好了。

1 个答案:

答案 0 :(得分:2)

我将用dict解析整个文件,而无需两次打开和迭代该文件:

result    = {}
current   = None
with open("my_file.txt") as fd: #To close the file automatically
    for line in fd:
        line = line.strip()
        if line.startswith('['):
            current = line.strip('[]')
            result[current] = []
            continue
        if current is None: continue
        if line: result[current].append(line)

 #Or just use the dictionary
 samp    = result['SAMP']
 samp_id = result['SAMP_ID']

如果您真的不想保留任何其他标签:

fields    = set(('SAMP','SAMP_ID'))
result    = {}
current   = None
with open("my_file.txt") as fd:
    for line in fd:
        line = line.strip()
        if line.startswith('['):
            current = line.strip('[]')
            if current not in fields: current = None
            else: result[current] = []
            continue
        if current is None: continue
        if line: result[current].append(line)