Amar Amar - 24 days ago 4
Python Question

Bring the cursor to start Of file in python

I want to save the unique words in my

myWords.txt
file. I am searching a word and if finds in the file, it does not write it, but if it does not find, it writes that word. The problem is, when I run the program second time, the pointer is at the end of file and search from the end of file and write the word again that wrote last time. I tried to use
seek(0)
at some positions but does not work. Am I doing something wrong?

with open("myWords.txt", "r+") as a:
# a.seek(0)
word = "naughty"
for line in a:
if word == line.replace("\n", "").rstrip():
break
else:
a.write(word + "\n")
print("writing " +word)
a.seek(0)
break

a.close()


myWords.txt

awesome
shiny
awesome
clumsy
shiny


On running code two times

myWords.txt

awesome
shiny
awesome
clumsy
shiny
naughty
naughty

Answer

You have wrong indention - now it finds different text in first line and automatically adds naughty because it doesn't check other lines.

You have to use for/else/break construction. else has the same indention as for.

If program find naughty then it use break to leave for loop and else will be skip. If for doesn't find naughty then it doesn't use break and then else will be executed.

with open("myWords.txt", "r+") as a:
    word = "naughty"
    for line in a:
        if word == line.strip():
            print("found")
            break
    else: # no break 
        a.write(word + "\n")
        print("writing:", word)

    a.close()

It works similar to

with open("myWords.txt", "r+") as a:
    word = "naughty"

    found = False

    for line in a:
        if word == line.strip():
            print("found")
            found = True
            break

    if not found:
        a.write(word + "\n")
        print("writing:", word)

    a.close()
Comments