0rdinal
0rdinal

Reputation: 661

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. 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 E.G: 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. E.G:

LMNO:
ABCD:
BABC:

So, if I wanted to delete the line containing ABCD or even ABCD:, it would return line 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)

Upvotes: 0

Views: 61

Answers (2)

Naggappan Ramukannan
Naggappan Ramukannan

Reputation: 2812

you can use slicing in python with delimiter as ':'

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)

Upvotes: 0

fboers
fboers

Reputation: 136

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)

Upvotes: 1

Related Questions