0

I'm trying to get my code to store messages within txt file using json. Each time a new message comes in, it will add the new message to the array.

The structure will be:

{
  "Messages": {
    "Test Contact 2": {
      "0": "\"Message 1"
    },
    "Test Contact 1": {
      "0": "\"Message 1\"",
      "1": "\"Message 2\""
    }
  }
}

And here is my current code:

class PluginOne(IPlugin):
    def process(self):
        try:
            print("Database")
            data_store('Test contact', 'Text Message')
            pass
        except Exception as exc:
            print("Error in database: " + exc.args)


def data_store(key_id, key_info):
    try:
        with open('Plugins/Database/messages.txt', 'r+') as f:
            data = json.load(f)
            data[key_id] = key_info
            f.seek(0)
            json.dump(data, f)
            f.truncate()
        pass
    except Exception as exc:
        print("Error in data store: " + exc.args)

when I try to run the code, I get the following error

Can't convert 'tuple' object to str implicitly
0

1 Answer 1

1

In your exception handler, you're adding exc.args to a string. The args attribute is a tuple, which can't be converted to a string implicitly. You could...

    # print it seperately
    print("Error in data store")
    print(exc.args)

    # or alternatively
    print("Error in data store: " + str(exc.args))

    # or alternatively
    print("Error in data store: " + str(exc))

However, this being a problem in the exception handler, the root cause of the problem is something else, and your current exception handler isn't that great at handling it:

  • without your exception handler, Python would show a complete traceback of the root cause of the exception, and halt your program.
  • with your exception handler, only your message is printed and the program continues. This might not be what you want.

It would perhaps be better to only catch the specific exceptions you know you can recover from.

Sign up to request clarification or add additional context in comments.

2 Comments

You can't concatenate strings and lists. You should find some way to represent the data you want from exc.args as a string instead.
Why would converting it to a list help? A list is also not a string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.