0

I would like to periodically check whether a certain word has been saved to a text file with python. Whenever I run the function it deletes anything in the text file regardless of what I tell it to look for specifically.

import threading

def ban():
        threading.Timer(0.1, ban).start()
        ff=open("htfl.txt","r")
        liney = ff.readlines()
        ff.close()
        ff=open("htfl.txt","w")
        for line in liney:
            if line!=("HTFL"):
                liney = liney[:-1]
                print("true")
ban()

It has to run every few seconds as it is part of an instant messenger I am working on which ought to ban rude words for example or certain usernames.

douglas rouse
  • 148
  • 1
  • 2
  • 15

2 Answers2

1
import threading

def ban():
        threading.Timer(0.1, ban).start()
        ff=open("htfl.txt","r")
        liney = ff.readlines()
        ff.close()
        ff=open("htfl.txt","w")
        for line in liney:
            if line!=("HTFL"):
                ff.write(line)
ban()

You opened the original file in write mode, which deletes everything. So you have to rewrite every line. Also doing liney[:-1] didn't make sense because your goal is to get rid of specific lines, not just mindlessly copy everything but the first line.

spicypumpkin
  • 1,209
  • 2
  • 10
  • 21
1

You can edit a file in-place using the fileinput module:

import threading
import fileinput
import time

def ban():
    for line in fileinput.input('htfl.txt', inplace=True):
        if line.rstrip() != "HTFL":
            print line,
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
  • Hi I am not familiar with that module, is it possible to do this without creating a new file? As in target an existing file? When I tried executing this i got an error: Cannot create a file when that file already exists: 'htfl.txt' -> 'htfl.txt.bak' – douglas rouse Feb 20 '17 at 23:46
  • See [the documentation](https://docs.python.org/2/library/fileinput.html#fileinput.FileInput), particularly the part about in-place filtering and the temporary backup filename. – Peter Wood Feb 20 '17 at 23:48
  • Not sure where I went wrong seems to be working well for me. I need to use threading though. If I have a .sleep in there it freezes my tkinter gui – douglas rouse Feb 20 '17 at 23:49
  • Okay, that's a different problem for another time. – Peter Wood Feb 20 '17 at 23:50