在 python 中删除 .txt 中的行

发布于 2025-01-09 05:36:48 字数 1432 浏览 0 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

她比我温柔 2025-01-16 05:36:48

如果您想要从某一行创建 .txt,这可能对您有用:

flag = false
with open("src.txt", "r") as src:
    with open("dst.txt", "w") as dst:
        for line in src:
            if(flag == True):
                dst.write(line)
            if(line.__contains__('ORIGIN')):
                flag = True

它会迭代源文件中的行,每当找到单词“ORIGIN”时,就会开始将 src 文件中的内容写入 dst 文件。

If what you want is to create a .txt from a certain line, this could work for you:

flag = false
with open("src.txt", "r") as src:
    with open("dst.txt", "w") as dst:
        for line in src:
            if(flag == True):
                dst.write(line)
            if(line.__contains__('ORIGIN')):
                flag = True

This iterates through the lines in the source file and whenever it finds the word 'ORIGIN' starts writing what's in the src file into the dst file.

叫思念不要吵 2025-01-16 05:36:48

看来您还想删除任何数字和斜杠。因此你可以这样做:

import re
import sys
with open('infile.txt', encoding='utf-8') as infile:
    try:
        while not next(infile).startswith('ORIGIN'):
            pass
        with open('outfile.txt', 'w', encoding='utf-8') as outfile:
            for line in infile:
                outfile.write(re.sub(r'[\d+|/]', '', line).lstrip())
    except StopIteration:
        print('ORIGIN not found', file=sys.stderr)

It seems that you also want to remove any numbers and slashes. Therefore you could do this:

import re
import sys
with open('infile.txt', encoding='utf-8') as infile:
    try:
        while not next(infile).startswith('ORIGIN'):
            pass
        with open('outfile.txt', 'w', encoding='utf-8') as outfile:
            for line in infile:
                outfile.write(re.sub(r'[\d+|/]', '', line).lstrip())
    except StopIteration:
        print('ORIGIN not found', file=sys.stderr)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文