2016-07-03 53 views
0

我试图让我的代码使用json在txt文件中存储消息。每次有新消息进入时,它都会将新消息添加到阵列中。Python:不能将'tuple'对象隐式转换为str

结构将是

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

这里是我当前的代码

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) 

当我尝试运行代码,我收到以下错误

Can't convert 'tuple' object to str implicitly 

我我在网上看起来还在挣扎,我敢肯定这是一个简单的答案,但由于我对Python相当陌生,所以我无法确定出来。

在先进的感谢

回答

1

在异常处理程序,您要添加exc.args为字符串。 args属性is a tuple,不能隐式转换为字符串。你可以...

# 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)) 

但是,这是在异常处理的一个问题,这个问题的根源是别的东西,而当前异常处理程序是不是在处理它是伟大的:

  • 没有你的异常处理程序,Python会显示异常的根本原因的完整回溯,并停止你的程序。
  • 您的异常处理程序,只有您的消息打印和程序继续。这可能不是你想要的。

这可能会更好,只有catch你知道你可以从中恢复的具体例外。

+0

您不能连接字符串和列表。你应该找到一些方法来代替你想从'exc.args'得到的数据。 – sidney

+0

为什么要将它转换为列表帮助?列表也不是字符串。 – khelwood

+0

你是对的。我已经解决了我的答案。 –

相关问题