r/badcode •

[deleted by user]

[deleted] — view deleted post

0 Upvotes

15 comments sorted by

View all comments

Show parent comment

1

u/gaberocksall May 25 '20 edited May 25 '20

I created the same thing but with slightly better practices and JSON just because i wanted to. All the same functionality but without the bugs and "features"

This is not a r/badcode entry, i just wanted to make a more realistic implementation of this project

import sys
import os
import json

dataFileName = "BBCC37data.json"
helpString = """
set <key> <value>    Sets <key> to <value>
get <key>            Prints the value saved in <key>, or "None"
delete <key>         Removes <key> from memory
keys                 Prints all known keys
"""

if not (os.path.exists(dataFileName) and os.path.isfile(dataFileName)):
    f = open(dataFileName, "w+")
    f.write("{\n}")
    f.close()

current_data = {}
with open(dataFileName, "r") as f:
    try:
        current_data = json.loads(f.read())
    except:
        print("Failed to read the data file '%s' as json" % dataFileName)  
        print("You could try to rebuild the file to save your data, or just delete it and start over")
        quit()

sysargs = sys.argv[1:]

if len(sysargs) == 0:
    quit(helpString)

requiredArgCounts = {
    "set": 2,
    "get": 1,
    "delete": 1,
    "keys": 0,
}

command, args = sysargs[0], sysargs[1:]
if not (command in requiredArgCounts):
    quit(helpString)

if len(args) != requiredArgCounts[command]:
    quit(helpString)

if command == "set":
    [key, value] = args
    current_data[key] = value
    with open(dataFileName, "w") as f:
        f.write(json.dumps(current_data, indent = 2))
elif command == "get":
    [key] = args
    print(current_data[key] if key in current_data else "None")
elif command == "delete":
    [key] = args
    if key in current_data:
        del current_data[key]
        with open(dataFileName, "w") as f:
            f.write(json.dumps(current_data, indent = 2))
else: #command = keys
    for key in current_data.keys():
        print(key)

0

u/AutoModerator May 25 '20

Hello gaberocksall,

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will render as broken gibberish on old reddit and some mobile apps.

Please edit the comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

Note: This filter is currently using new regex in an attempt to reduce false positives. Please report any anomalies to the mods.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.