【问题标题】:Delete a certain line in text file if user input string matches如果用户输入字符串匹配,则删除文本文件中的某一行
【发布时间】:2020-04-04 02:22:59
【问题描述】:

如果用户输入的string存在于文本文件中,程序应该在文本文件中找到/return行号printline number

kw 是用户输入 btw

一些代码供参考:

def DELITEM():
            kw = Dele.get()
            with open('notify.txt') as f:
                if kw in f.read:
                    print('the number of the line kw is in')

【问题讨论】:

标签: python python-3.x file


【解决方案1】:

我猜你可以这样做:

with open('notify.txt', 'r') as f:
    for num, line in enumerate(f):
        if kw==line:
            print(num)

这里enumerate() 在文件中添加了一个计数器,允许您识别行。

【讨论】:

    【解决方案2】:

    您可以遍历这些行,直到找到 readlines

    DELITEM():
        kw = Dele.get() 
        with open('notify.txt', 'r') as f:
            if kw in f.read:
                lines = f.readlines()
                for i in range(len(lines)):
                    if kw in lines[i]:
                        print("The line is",i)
                        break
    

    要从文本文件中删除该行,方法是删除列表中的行,然后将这些行写回文件中。所以像这样的

    del lines[i]
    

    然后在你写的地方再写一个

    with open('notify.txt', 'w') as f:
        for line in lines:
            f.write(line + '\n')
    

    所以把它放在一起

    DELITEM():
            lines = []
            kw = Dele.get() 
            with open('notify.txt', 'r') as f:
                if kw in f.read:
                    lines = f.readlines()
                    for i in range(len(lines)):
                        if kw in lines[i]:
                            print("The line is",i)
                            del lines[i]
                            break
            with open('notify.txt', 'w') as f:
            for line in lines:
                f.write(line + '\n')
    

    【讨论】:

    • 但问题不在于找到该行,问题是我不知道如何从文本文件中删除该行
    猜你喜欢
    • 2022-10-15
    • 2013-04-06
    • 2021-04-17
    • 2014-08-11
    • 1970-01-01
    • 2019-12-17
    • 2020-11-19
    • 1970-01-01
    • 2011-09-25
    相关资源
    最近更新 更多