0
d = feedparser.parse('somerssfeed/rss.xml')
message = {}
smessage = {}

for post in d.entries:
    message[post.link] = post.title

fwrite = open("db.txt", "a")

for k, v in message.items():
    if k in open("db.txt", "r"):
        print("already exists")
    else:
        fwrite.write("\n" + "{0}".format(k) + "\n")
        smessage[k] = v

What i want to achieve is parsing RSS feeds and write their links in to a text file. But the problem is when i run the script next time it should't return old rss items so i compare them via text file except it's failing. On the first run it writes all links, second run it should return empty because all of links are the same but it writes again the same links

EDIT:

after a whole day of trial and error this worked:

for k, v in message.items():
    if k in open('db.txt').read():
        print('already exists')
    else:
        smessage[k] = v
        fwrite = open("db.txt", "a")
        fwrite.write('\n{0}\n'.format(k))
        fwrite.close()
ggnoredo
  • 801
  • 1
  • 13
  • 33
  • Welcome to SO. Please take the time to read [ask] and the links it contains. – wwii Sep 29 '17 at 14:52
  • 1
    As an aside: Since you are already using `str.format` - `("\n" + "{0}".format(k) + "\n")` can also be written as `("\n{0}\n".format(k))`. – wwii Sep 29 '17 at 14:54

1 Answers1

1

You aren't using the correct syntax to open the file. Use this :

g = open("db.txt","r")
lines = xml_file.readlines()
if k in lines: 
    print ("already exists");
Abhay Sibal
  • 129
  • 1
  • 12
  • it still re-inserting same results – ggnoredo Sep 29 '17 at 14:39
  • OP is formatting the string before writing it, maybe `k` needs to be formatted also to be equivalent. You probably want to just call `.readlines()` once and assign it to a name instead of calling it for every `k`'. – wwii Sep 29 '17 at 14:50
  • Try the new code that I've added, based on @wwii 's comment – Abhay Sibal Sep 29 '17 at 15:41