Python打印新行

时间:2017-06-19 19:17:03

标签: json python-3.x

有人可以解释为什么下面脚本第17行的这个字符在新行上打印了吗?

from pathlib import Path

pathList = Path("states").glob("**/*.*")
OUT = open("resources/states.json", "w")

OUT.write("{\n")
for path in pathList:
    F = open(str(path),"r")
    L = F.readlines()
    OUT.write("\"" + str(path) + "\":\n")
    OUT.write("[\n")
    for l in L:
        s = l.split("=")
        print(s)
        OUT.write("{")
        OUT.write(" \"name\": " + "\"" + s[0] + "\"" + ",\n")
        OUT.write(" \"code\": " + "\"" + (s[0] if len(s) == 1 else s[1]) + "\"")
        OUT.write("}" + ("" if l == L[-1] else ",") +  "\n")
    OUT.write("],\n\n")
    F.close()
OUT.write("}\n")
OUT.flush()
OUT.close()

输出:

{
    "states/APO_states.txt": [
        {
            "name": "Armed Forces Americas",
            "code": "AA
"
        },
        {
            "name": "Armed Forces",
            "code": "AE
"
        },

    ...

有什么问题?我试图冲洗它,但它没有帮助。

2 个答案:

答案 0 :(得分:2)

这是因为L = F.readlines()看起来像['key1=value1\n', ...(注意\n,它不会消失; \r\n也可能代替),所以s = l.split("=")是比如['key1', 'value1\n']。解决方案:s = l.strip().split("=")

答案 1 :(得分:1)

根据您的问题,您想要撰写JSON。不要自己编写编码器和解码器,而是最好使用模块,因为它可以保证输出有效。

因此,我们必须构建一个程序来构造一个带有data的字典sublist,每个字典都包含一个带有dict'name'键的'code'离合器。完成后,我们可以将相应的JSON写入OUT文件处理程序。

from pathlib import Path
import json

pathList = Path("states").glob("**/*.*")
with open("resources/states.json", "w") as OUT:
    data = {}
    for path in pathList:
        with open(str(path),"r") as F:
            sublist = []
            for l in F:
                s = l.strip().split("=")
                print(s)
                sublist.append({'name':s[0],'code':s[0] if len(s) == 0 else s[1]})
        data[str(path)] = sublist
    json.dump(data,OUT)

您最好还使用with语句,因为这些语句会在您离开with范围后自动刷新并关闭文件。