有人可以解釋爲什麼下面的腳本中第17行的char被打印在新行上?Python打印新行
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()
OUTPUT:
{
"states/APO_states.txt": [
{
"name": "Armed Forces Americas",
"code": "AA
"
},
{
"name": "Armed Forces",
"code": "AE
"
},
...
有什麼不對?我試圖沖洗它,但它沒有幫助。
你能解釋爲什麼你不使用爲此設計的模塊 - ['json'](https://docs.python.org/3/library/json.html)? – zwer
'print'自動以換行符結束。如果你想避免這種情況,使用'print(...,end ='')' – inspectorG4dget
對不起,但我正在使用寫入,而不是打印。最後一個字符「\」「應該包含在行結束之前,對嗎? – user2908112