我如何在Python中指明字符串中的换行符,以便我可以将多行写入文本文件?
当前回答
\n分隔字符串的行。在下面的示例中,我一直在循环中写入记录。每条记录以\n分隔。
f = open("jsonFile.txt", "w")
for row_index in range(2, sheet.nrows):
mydict1 = {
"PowerMeterId" : row_index + 1,
"Service": "Electricity",
"Building": "JTC FoodHub",
"Floor": str(Floor),
"Location": Location,
"ReportType": "Electricity",
"System": System,
"SubSystem": "",
"Incomer": "",
"Category": "",
"DisplayName": DisplayName,
"Description": Description,
"Tag": tag,
"IsActive": 1,
"DataProviderType": int(0),
"DataTable": ""
}
mydict1.pop("_id", None)
f.write(str(mydict1) + '\n')
f.close()
其他回答
各种等效方法
使用打印
默认情况下,打印已经追加了换行符!
with open("out.txt", "w") as f:
print("First", file=f)
print("Second", file=f)
等同于:
with open("out.txt", "w") as f:
print("First\nSecond", file=f)
要打印而不自动添加换行符,使用sep=""(因为sep="\n"是默认值):
with open("out.txt", "w") as f:
print("First\nSecond\n", sep="", file=f)
使用f.write
对于以文本模式打开的文件:
with open("out.txt", "w") as f:
f.write("First\nSecond\n")
对于以二进制模式打开的文件,写入文件时不会自动将\n转换为特定于平台的行结束符。要强制使用当前平台的换行符,请使用os。Linesep代替\n:
with open("out.txt", "wb") as f:
f.write("First" + os.linesep)
f.write("Second" + os.linesep)
输出文件
视觉:
First
Second
在Linux上,换行符将以\n分隔:
First\nSecond\n
在Windows中,换行符将以\r\n分隔:
First\r\nSecond\r\n
为了避免以文本模式打开的文件自动将\n转换为\r\n,请使用open("out.txt", "w", newline="\n")打开文件。
'\n'也是一样,不过你可能不需要'\r'。在Java版本中使用它的原因是什么?如果你确实需要/想要它,你也可以在Python中以同样的方式使用它。
在Python中,你可以只使用换行符,即\n
这取决于你想要多正确。\n通常会做这项工作。如果你真的想要正确,你可以在os包中查找换行符。(这实际上叫做linesep。)
注意:当使用Python API写入文件时,不要使用os.linesep。只使用\n;Python会自动将其转换为适合您平台的换行符。
Java字符串文字中的大多数转义字符在Python中也有效,例如“\r”和“\n”。