python读取文件,用条件绘制线

2024-04-24 11:46:25 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个文件my_file,我希望从中获得某些行,例如,其中每行输出都是一个列表元素。我试图理解如何控制和使用Python文件I/o操作

文件:

cat > my_file <<EOF
[Ignore_these] 
abc
234
[Wow]
123
321
def
[Take_rest]
ghi
jkl
EOF

比如说,在第[Wow]行之后,我想合并整数行(可以是任意数量的行,这里我得到'123321'),忽略其余的行,直到我遇到[Take_rest],从那里我想要剩余的行('ghi'和'jkl')-[Take_rest]总是最后一部分。因此,结果输出为data = list('123321', 'ghi', 'jkl')。 我尝试了以下类似的方法,但未能理解readline()next()(etc)是如何工作的

def is_int(s):
    try:
        int(s)
        return True
    except ValueError:
        return False


with open('my_file', 'r') as f:
    data = []
    while True:
        line = f.readline()
        if '[Wow]' in line:
            wow = ''
            while is_int(next(f)):
                wow = ''.join([wow, line])
            data.append(wow)
        if '[Take_rest]' in line:
            data.append(next(f))

        if not line:
            break

Tags: 文件restdataifmylinejklfile
1条回答
网友
1楼 · 发布于 2024-04-24 11:46:25

不要使事情复杂化-使用以下方法:

with open('input.txt') as f:
    data = ['']
    wow_flag = False
    for line in f:
        line = line.strip()
        if line.startswith('[Wow]'):   # detect `Wow` section start
            wow_flag = True
        elif line.startswith('[Take_rest]'):  # taking all the rest
            data.extend(list(line.strip() for line in f))
        if wow_flag and line.isdigit():   # capturing digits under `Wow` section
            data[-1] += line

print(data)

输出:

['123321', 'ghi', 'jkl']

相关问题 更多 >