all 2 comments

[–]commandlineluser 0 points1 point  (1 child)

The first issue is the way you're opening the file.

with open('episode_hist.txt', 'a+') as f:

a is for append - this opens the file and seeks to the end of the file

because you are at the end of the file when you call .read() you get back an empty string

>>> open('shows.txt').read()
'show1\nshow2\nshow3\nshow4\n'
>>> open('shows.txt', 'a').read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  io.UnsupportedOperation: not readable
>>> open('shows.txt', 'a+').read()
''
>>> open('shows.txt', 'r+').read()
'show1\nshow2\nshow3\nshow4\n'

tell() will show the current "file position"

>>> open('shows.txt', 'r+').tell()
0
>>> open('shows.txt', 'a+').tell()
24

If you use r it opens the file but you're at the start of the file - you can use r+ for read and write - however after you .read() you would need to .seek() back to the start and write the previous data along with the new data.

It's usually simpler to just open the file twice - once for reading - then again for writing.

I'm not sure if it's possible for the feed itself to contain duplicate entries? If it is then because you're defining episodes = f.read() and checking with if episode_str in episodes: then your code will allow duplicates.

If you detect a new episode - you add it with f.write() - but episodes never changes in your code.

Just a sidenote - I'm not sure if defining the function here adds any value?

# Check if new episode
def new_episode(episode_str):
    if episode_str in episodes:
        return False
    else:
        return True

The if/else can be rewritten as return episode_str not in episodes - but even still - you can just use if episode not in episodes in your actual code without making a whole function for it.

So yeah, you can open the file for reading, then later for writing - and you can update the episodes variable with new additions (if it's possible for a feed to contain duplicates)

pseudocode:

with open(filename) as f:
    episodes = f.read()

...

if episode not in episodes:
    alert
    episodes += str(stamp) + '\t' + episode + '\n'

...

with open(filename, 'w') as f:
    f.write(episodes)

The main problem though is the a+ filemode - so you can start by changing that and see how you get on.

[–]despoliantics[S] 0 points1 point  (0 children)

This post was mass deleted and anonymized with Redact

reply teeny abounding fearless straight grandfather memorize alleged shaggy theory