繁体   English   中英

如何在python中的文本文件中删除特定单词之前的一行

[英]How to delete one line before a specific word in a text file in python

所以我有文本文件file.txt例如

something1
something2
something3
line to be removed
2022-07-21 >>  Ctrl+S
something4
something5
something6
something7
line to be removed
2022-07-21 >>  Ctrl+S

现在如何让它在整个文件中删除Ctrl+S之前一行

这样输出文件将是

something1
something2
something3
2022-07-21 >>  Ctrl+S
something4
something5
something6
something7
2022-07-21 >>  Ctrl+S

谢谢

也许这会帮助你:

import re

with open('file.txt') as f:
    text = f.read()

text = re.sub(r'(Ctrl\+S)(\n[^\n]+)(?=\nCtrl\+S)', '\\1\\3', text)

with open('file.txt', 'w') as f:
    f.write(text)
f = open("file.txt",'r')
lines = f.readlines()
f.close()

excludedWord = "whatever you want to get rid of"

newLines = []
for line in lines:
    newLines.append(' '.join([word for word in line.split() if word != 
    excludedWord]))

f = open("file.txt", 'w')
for line in lines:
f.write("{}\n".format(line))
f.close()

这可能有点用!

# open two files: one for reading, one for writing
with open('file.txt', 'rt') as in_, open('out.txt', 'wt') as out:
    # if we're considering two lines, we have to store the other one
    old_line = None
    for line in in_:  # iterating over a text file gives lines
        if old_line is not None and line != "Ctrl+S\n":
            # we can write the previous line each iteration
            out.write(old_line)
        old_line = line
    if old_line is not None:
        # but we have to make sure to write the last one,
        # since it's never the previous line
        out.write(old_line)

这种方法不会将整个文件存储在内存中,因此它适用于较大的文件——只要一行不是太长,就是这样!

回答

keyword = 'Ctrl+S'
new_content = []

with open('textfile.txt', 'r+') as f:
    content = f.readlines()
    prev_index = 0
    for i, line in enumerate(content):
        if keyword in line:
            new_content += content[prev_index:i - 1]
            prev_index = i
    new_content += content[prev_index:]
with open('textfile.txt', 'w') as f:
    f.write("".join(new_content))

感谢并感谢@AndersHaarbergEriksen 先生

link https://stackoverflow.com/a/73070745/19284077

或单开

with open("textfile.txt", "r+") as f:
    lines = f.readlines()
    f.seek(0)
    for pos, line in enumerate(lines):
        if len(lines)-1 !=pos:
            if "Ctrl+S" in lines[pos+1]:
                continue
        f.write(line)
    f.truncate()

致谢:@Ameen Ali Shaikh

link https://stackoverflow.com/a/73070970/19284077

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM