简体   繁体   English

搜索文本文件的特定行,但会令人讨厌

[英]searching a specific line of a text file, but with an annoying twist

So, my python file needs to be able to delete lines of a text file. 因此,我的python文件需要能够删除文本文件的行。 Easy right? 容易吧? There are loads of answered questions on this website on this topic, unfortunately, they don't include if two line have the same series of characters inside of the string EG: datafile.txt: 很遗憾,此网站上有很多关于此主题的已回答问题,但是,如果字符串EG中的两行包含相同的一系列字符,则不包括这些问题: datafile.txt:

LMNO:ABCD:UVWX
ABCD:EFGH:IJKL
BABC:DEFG:HIJK

If I wanted to delete line two, I would have to search for it, The way my system works means that you will only know the first section before the colon. 如果要删除第二行,则必须进行搜索。系统的工作方式意味着您将只知道冒号之前的第一部分。 EG: 例如:

LMNO:
ABCD:
BABC:

So, if I wanted to delete the line containing ABCD or even ABCD:, it would return line 1. 因此,如果我想删除包含ABCD甚至ABCD:的行,它将返回第1行。

This is my current code: 这是我当前的代码:

import fileinput, sys
def searchFiles(searchPrompt):
    with open("testfile.txt") as f:
        for num, line in enumerate(f, 1):
            if searchPrompt in line:
                return(num)

def deleteLine(lineNumber):
    for lineNumber, line in enumerate(fileinput.input('testfile.txt', 
    inplace=1)):
        if lineNumber == 0:
            continue
        else:
            sys.stdout.write(line)   

searchPrompt = input("Enter username to delete: ")
searchPrompt = (searchPrompt+":")
print(searchPrompt)
lineNumber = searchFiles(searchPrompt)
deleteLine(lineNumber)

I think this is what you want: 我认为这是您想要的:

import fileinput, sys

def removeFromFile(file, user):
    pattern = user+":"
    f = open(file, "r+")
    lines = f.readlines()
    f.seek(0)
    for line in lines:
        if not line.startswith(pattern):
            f.write(line)
    f.truncate()
    f.close()

username = input("Enter username to delete: ")
removeFromFile("datafile.txt", username)

you can use slicing in python with delimiter as ':' 您可以在带分隔符的python中使用切片:

Eg: 例如:

def searchFiles(searchPrompt):
    with open("testfile.txt") as f:
        for num, line in enumerate(f, 1):
            if searchPrompt == line.split(":")[0]:
                return(num)

def deleteLine(lineNumber):
    for lineNumber, line in enumerate(fileinput.input('testfile.txt', 
inplace=1)):
        if lineNumber == 0:
            continue
        else:
            sys.stdout.write(line)   

searchPrompt = input("Enter username to delete: ")
searchPrompt = searchPrompt.split(":")[0]
print(searchPrompt)
lineNumber = searchFiles(searchPrompt)
deleteLine(lineNumber)

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

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