加入值列表后写入文件时出错

use*_*103 0 python

我试图在加入一个文件后遇到列表的某些值并遇到以下错误,如何解决这个问题的任何输入?

data_changes ={'305403': ['302180'], '312994': ['311957'], '311957': ['312621'] }
modem_changes = {'305403': [], '313113': [], '312994': ['253036', '312591'], '311957': []}

dc_set = set(data_changes)
mc_set = set(modem_changes)

with open('file.txt', 'w+') as f:
    for key in dc_set.intersection(mc_set):
        union_values = data_changes[key] + modem_changes[key]
        values = key, ','.join(union_values)
        f.write(values)

with open('file.txt', 'a') as f:
    for key in dc_set.symmetric_difference(mc_set):
        dc_values = data_changes.get(key) or []
        mc_values = data_changes.get(key) or []
        union_values = dc_values + mc_values
        values=key, ','.join(union_values)
        f.write(values)
Run Code Online (Sandbox Code Playgroud)

错误:-

Traceback (most recent call last):
  File "final_build_list.py", line 31, in <module>
    f.write(values)
TypeError: argument 1 must be string or read-only character buffer, not tuple
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 5

values=key, ','.join(union_values)tuple不是string,你不能写一个文件的元组.

>>> foo = 1,2 # comma separated values on RHS are converted to tuple
>>> type(foo)
<type 'tuple'>
Run Code Online (Sandbox Code Playgroud)

可能你在寻找:

values= "{0}, {1}\n".format(key, ','.join(union_values))
Run Code Online (Sandbox Code Playgroud)

例:

data_changes ={'305403': ['302180'], '312994': ['311957'], '311957': ['312621'] }
modem_changes = {'305403': [], '313113': [], '312994': ['253036', '312591'], '311957': []}

dc_set = set(data_changes)
mc_set = set(modem_changes)

with open('abc', 'w+') as f:
    for key in dc_set.intersection(mc_set):
        union_values = data_changes[key] + modem_changes[key]
        values= "{0}, {1}\n".format(key, ','.join(union_values))
        f.write(values)
Run Code Online (Sandbox Code Playgroud)

输出(abc的内容):

311957, 312621
305403, 302180
312994, 311957,253036,312591
Run Code Online (Sandbox Code Playgroud)