0

If that string input by User exists in text file, the program should find/return line number in text file and print the line number

kw is the user input btw

some code for reference:

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')
Susobhan Das
  • 247
  • 2
  • 17
  • Does this answer your question? [Deleting certain line of text file in python](https://stackoverflow.com/questions/12116752/deleting-certain-line-of-text-file-in-python) – Joshua Hall Apr 04 '20 at 03:36

2 Answers2

0

I guess you could do something like:

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

Here enumerate() adds a counter to the file that allows you to identify lines.

NotAName
  • 3,821
  • 2
  • 29
  • 44
0

you could loop through the lines until you find it with 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

To delete the line from the text file, on way would be to delete the line in the list then write the lines back onto the file. So something like this

del lines[i]

then have another with where you write

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

so putting this altogether you have

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')
The Big Kahuna
  • 2,097
  • 1
  • 6
  • 19