如何更改文件写入功能以便写入“;”当它在“(”“)”里面时,而不是“,”?

时间:2017-12-14 18:14:33

标签: python file-writing

这就是我的功能写作:

Marianne Thibault, french, ('phones',), 11:09, 230

这就是我想要写的:

Marianne Thibault, french, (phones; computers), 11:09, 230

这是我正在使用的功能:

 header='\n'.join(header)
        out_file=open(file_name,'w')
        out_file.write(str(header)+ '\n')
        out_file.write('Operators:'+'\n')
        for i in range(len(operators)):
                out_file.write(', '.join(map(str, operators[i])))
                out_file.write('\n')
        out_file.close()

1 个答案:

答案 0 :(得分:1)

with open(file_name, 'w') as out_file:
    out_file.write('\n'.join(header))
    out_file.write('\nOperators:\n')
    for operator in operators:
        formatted_fields = []
        for field in operator:
            if isinstance(field, tuple):
                semi_delimited_field = '; '.join(str(x) for x in field)
                field_in_parens = '(' + semi_delimited_field + ')'
                formatted_fields.append(field_in_parens)
            else:
                formatted_fields.append(str(field))
        out_file.write(', '.join(formatted_fields))
        out_file.write('\n')