与 Java(在字符串中)相比,您会执行类似"First Line\r\nSecond Line"
.
那么,为了将多行写入常规文件,您将如何在 Python 中执行此操作?
与 Java(在字符串中)相比,您会执行类似"First Line\r\nSecond Line"
.
那么,为了将多行写入常规文件,您将如何在 Python 中执行此操作?
这取决于你想要的正确程度。\n
通常会完成这项工作。os
如果你真的想把它弄对,你可以在package中查找换行符。(它实际上被称为linesep
。)
注意:使用 Python API 写入文件时,不要使用os.linesep
. 只需使用\n
; Python 会自动将其转换为适合您平台的换行符。
换行符是\n
. 它在字符串中使用。
例子:
print('First line \n Second line')
\n
换行符在哪里。
这将产生结果:
First line
Second line
如果您使用 Python 2,则不要在 print 函数上使用括号。
您可以单独写入新行,也可以在单个字符串中写入,这更容易。
line1 = "hello how are you"
line2 = "I am testing the new line escape sequence"
line3 = "this seems to work"
您可以单独编写 '\n':
file.write(line1)
file.write("\n")
file.write(line2)
file.write("\n")
file.write(line3)
file.write("\n")
hello how are you
I am testing the new line escape sequence
this seems to work
正如其他人在前面的答案中指出的那样,将 \n 放在字符串中的相关点:
line = "hello how are you\nI am testing the new line escape sequence\nthis seems to work"
file.write(line)
hello how are you
I am testing the new line escape sequence
this seems to work
独立于平台的断线器:Linux,windows & IOS
import os
keyword = 'physical'+ os.linesep + 'distancing'
print(keyword)
输出:
physical
distancing
编辑:我现在年纪大了,也更聪明了。这是一个更具可读性的解决方案,即使您不是顶级缩进(例如在函数定义中),它也能正常工作。
import textwrap
file.write(textwrap.dedent("""
Life's but a walking shadow, a poor player
That struts and frets his hour upon the stage
And then is heard no more: it is a tale
Told by an idiot, full of sound and fury,
Signifying nothing.
"""))
原始答案
如果您一次输入多行文本,我发现这是最易读的格式。
file.write("\
Life's but a walking shadow, a poor player\n\
That struts and frets his hour upon the stage\n\
And then is heard no more: it is a tale\n\
Told by an idiot, full of sound and fury,\n\
Signifying nothing.\n\
")
每行末尾的 \ 转义新行(这会导致错误)。
如果只调用print
不带任何参数,它将输出一个空行。
print
您可以将输出通过管道传输到这样的文件(考虑您的示例):
f = open('out.txt', 'w')
print 'First line' >> f
print >> f
print 'Second line' >> f
f.close()
它不仅与操作系统无关(甚至不必使用os
包),而且比放入\n
字符串更具可读性。
该print()
函数有一个用于字符串结尾的可选关键字参数,称为end
,默认为操作系统的换行符,例如。\n
. 因此,当您调用 时print('hello')
,Python 实际上是在打印'hello' + '\n'
. 这意味着当您在print
没有任何参数的情况下调用时,它实际上是正在打印'' + '\n'
,这会导致换行。
使用多行字符串。
s = """First line
Second line
Third line"""
f = open('out.txt', 'w')
print s >> f
f.close()
在 Python 中,您可以只使用换行符,即\n
正如其他答案中提到的:“换行符是 \n。它在字符串中使用”。
我发现最简单易读的方法是使用“格式”函数,使用 nl 作为新行的名称,并将要打印的字符串分解为要打印的确切格式:
蟒蛇2:
print("line1{nl}"
"line2{nl}"
"line3".format(nl="\n"))
蟒蛇3:
nl = "\n"
print(f"line1{nl}"
f"line2{nl}"
f"line3")
这将输出:
line1
line2
line3
这样它执行任务,并且还提供了代码的高可读性:)
与 相同的方式'\n'
,尽管您可能不需要'\r'
. 你的Java版本中有它的原因吗?如果你确实需要/想要它,你也可以在 Python 中以同样的方式使用它。
Java 字符串文字中的大多数转义字符在 Python 中也是有效的,例如“\r”和“\n”。
\n - 简单的换行符插入工作:
# Here's the test example - string with newline char:
In [36]: test_line = "Hi!!!\n testing first line.. \n testing second line.. \n and third line....."
# Output:
In [37]: print(test_line)
Hi!!!
testing first line..
testing second line..
and third line.....
值得注意的是,当您使用交互式 python shell 或 Jupyter 笔记本检查字符串时,\n
和其他反斜杠字符串如字面意思\t
呈现:
>>> gotcha = 'Here is some random message...'
>>> gotcha += '\nAdditional content:\n\t{}'.format('Yet even more great stuff!')
>>> gotcha
'Here is some random message...\nAdditional content:\n\tYet even more great stuff!'
换行符、制表符和其他特殊的非打印字符仅在打印或写入文件时呈现为空白:
>>> print('{}'.format(gotcha))
Here is some random message...
Additional content:
Yet even more great stuff!
在 Python 3 中,该语言会在平台的本机表示中为您编码换行符。这意味着\r\n
在 Windows 上,并且只是\n
在成熟的系统上。
即使在 U*x 系统上,以文本模式读取具有 Windows 行结尾的文件也会返回正确的文本结果,即在字符被静默删除\r
之前的任何字符。\n
如果您需要完全控制文件中的字节,您可以使用二进制模式。然后每个字节正好对应一个字节,Python 不执行翻译。
>>> # Write a file with different line endings, using binary mode for full control
>>> with open('/tmp/demo.txt', 'wb') as wf:
... wf.write(b'DOS line\r\n')
... wf.write(b'U*x line\n')
... wf.write(b'no line')
10
9
7
>>> # Read the file as text
>>> with open('/tmp/demo.txt', 'r') as text:
... for line in text:
... print(line, end='')
DOS line
U*x line
no line
>>> # Or more demonstrably
>>> with open('/tmp/demo.txt', 'r') as text:
... for line in text:
... print(repr(line))
'DOS line\n'
'U*x line\n'
'no line'
>>> # Back to bytes!
>>> with open('/tmp/demo.txt', 'rb') as binary:
... for line in binary:
... print(line)
b'DOS line\r\n'
b'U*x line\n'
b'no line'
>>> # Open in binary, but convert back to text
>>> with open('/tmp/demo.txt', 'rb') as binary:
... for line in binary:
... print(line.decode('utf-8'), end='')
DOS line
U*x line
no line
>>> # Or again in more detail, with repr()
>>> with open('/tmp/demo.txt', 'rb') as binary:
... for line in binary:
... print(repr(line.decode('utf-8')))
'DOS line\r\n'
'U*x line\n'
'no line'
\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()
"{}\n{}\n{}".format(
"line1",
"line2",
"line3"
)
个人比较喜欢这种格式