-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Totally rewritten update to eliminate the issue of duplicates
- Loading branch information
1 parent
12da103
commit a41e71b
Showing
1 changed file
with
32 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,34 @@ | ||
import secrets | ||
# using secrets for better entropy, otherwise it picks the same quotes over and over | ||
import random | ||
import os | ||
import json | ||
|
||
text_file = open("quotes.txt") | ||
line = text_file.readlines() | ||
# New version rewritten from the ground up | ||
# Ensures that there are no duplicates by creating a new list of quotes and deleting quotes from that list after the script has been run | ||
# Doesn't touch the original quotes file, it copies the contents to the temp file after shuffling them, then reads from the temp file and deletes quotes from that | ||
# Once the temp file is empty the script will delete it, then on the next run it creates a new temp file and starts again | ||
|
||
print(secrets.choice(line)) | ||
text_file.close() | ||
# Temp file must be written to disk for persistance between runs | ||
quotes_file = "quotes.txt" | ||
temp_file = "temp_quotes.txt" | ||
|
||
def get_quote(): | ||
if os.path.exists(temp_file): | ||
with open(temp_file, 'r') as f: | ||
lines = json.load(f) | ||
else: | ||
with open(quotes_file, 'r') as f: | ||
lines = f.readlines() | ||
random.shuffle(lines) | ||
|
||
quote = lines.pop() | ||
|
||
# If the list is empty delete temp file, else write the remaining quotes (minus the one just used) back | ||
if not lines: | ||
os.remove(temp_file) | ||
else: | ||
with open(temp_file, 'w') as f: | ||
json.dump(lines, f) | ||
|
||
return quote | ||
|
||
print(get_quote()) |