如何将键,值格式更改回行?

时间:2015-12-14 17:17:15

标签: python

file_name.txt包含

{'email1234': 'OK', 'email03': 'SPAM', 'email02': 'OK', 'email01': 'OK'}

我的代码

def write_classification_to_file(fpath1,fpath2):

    f = open('file_name.txt', "r")
    xs = f.readlines()




    g = open('file_write.txt', "w")
    for v in xs:
     g.write(v)
    return g

我正在尝试将filename.txt中的文本写入file_write.txt但是通过删除file_name.txt的键和值并将它们连接在一起到目前为止我设法将其打印在那里但是与file_name.txt相同我得到了< / p>

file_write.txt中的预期输入

email01 OK
email02 OK
email03 SPAM
email1234 OK

2 个答案:

答案 0 :(得分:3)

该文件似乎不是严格的json格式,但ast.literal_eval将处理Python字典语法:

import ast
with open('file_name.txt') as f:
    D = ast.literal_eval(f.read())
with open('file_write.txt','w') as f:
    for k,v in D.items():
        f.write('{} {}\n'.format(k,v))

输出:

email02 OK
email1234 OK
email03 SPAM
email01 OK

如果按键排序很重要,您可以使用for k,v in sorted(D.items()):

答案 1 :(得分:1)

您正在寻找的可能是json解码。

import json
def write_classification_to_file(file_name_in, file_name_out):
    with open('file_name.txt', "r") as f_in:
        xs = json.loads(f_in.read())
    with open('file_write.txt', "w") as f_out:
        for key in sorted(xs.keys()):
            f_out.write("{} {}\n".format(key, xs[key]))