python读取文本文件中的每一行,并将开始和结束之间的任何内容放入一个新的fi中

2024-04-26 09:30:34 发布

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

我有一个文本文件,我已经导入没有空行,看起来像这样。。。这些东西都在一条单独的线上。你知道吗

--START--some data
one line
two line
three line
--END--
four
five
--START-- some data
six 
seven
eight
--END--
nine 
ten
eleven
--START-- some data

我想要什么

我已经编写了代码来打开文件,循环遍历每一行并找到包含start的行。你知道吗

import codecs
file = codecs.open('data.txt', encoding='utf-8').read()
for line in file:

    if '--START--' in line:
    #found the start line (keep all lines until you find END)

我不知道如何在python中创建逻辑,其中以START开头或其后的每一行(直到但不包括结束行)进入一个新的文本文件。你知道吗

所以我会以新文件.txt仅包含:

--START--some data
one line
two line
three line
--START-- some data
six 
seven
eight
--START-- some data

Tags: 文件datalinesomeonestartendthree
3条回答

你的意思是

file_contents = open('data.txt',"rb").read()
with open("newfile.txt","wb") as f:
      f.write(" START ".join(p.split(" END ")[0] for p in file_contents.split(" START ")))

这个怎么样?你知道吗

import codecs
file = codecs.open('data.txt', encoding='utf-8').read()
startblock = 0
for line in file:
    if ' END ' in line:
        startblock = 0
    elif ' START ' in line or startblock:
        # Write to file
        startblock = 1
from  itertools import takewhile
with open("in.txt") as f:
    final = []
    for line in f:
        if line.startswith(" START "):
            final += [line] + list(takewhile(lambda x: not x.startswith(" END "),f))
print(final)
[' START some data\n', 'one line\n', 'two line\n', 'three line\n', ' START  some data\n', 'six \n', 'seven\n', 'eight\n', ' START  some data']

要写入新数据:

from  itertools import takewhile
with open("in.txt") as f,open("out.txt","w") as f1:
    for line in f:
        if line.startswith(" START "):
            f1.write(line + "".join(list(takewhile(lambda x: not x.startswith(" END "),f))))

相关问题 更多 >