我如何在Python中指明字符串中的换行符,以便我可以将多行写入文本文件?
这取决于你想要多正确。\n通常会做这项工作。如果你真的想要正确,你可以在os包中查找换行符。(这实际上叫做linesep。)
注意:当使用Python API写入文件时,不要使用os.linesep。只使用\n;Python会自动将其转换为适合您平台的换行符。
新的行字符是\n。它用于字符串内部。
例子:
print('First line \n Second line')
其中\n是换行符。
这将产生如下结果:
First line
Second line
如果使用Python 2,则不对打印函数使用圆括号。
您可以单独写入新行,也可以在单个字符串中写入,这样更容易。
示例1
输入
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
示例2
输入
正如其他人在之前的回答中指出的那样,将\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
这里有一个更易读的解决方案,即使你不在顶级缩进(例如,在函数定义中),它也能正确工作。
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.
"""))
简单的解决方案
如果只调用print而不带任何参数,它将输出一个空行。
print
你可以像这样将输出管道到一个文件中(考虑到你的例子):
f = open('out.txt', 'w')
print 'First line' >> f
print >> f
print 'Second line' >> f
f.close()
它不仅与操作系统无关(甚至不需要使用操作系统包),而且比将\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()
\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....."
输出:
In [37]: print(test_line)
Hi!!!
testing first line..
testing second line..
and third 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()
与平台无关的断行符:Linux、Windows和iOS
import os
keyword = 'physical'+ os.linesep + 'distancing'
print(keyword)
输出:
physical
distancing
正如在其他回答中提到的:“新的行字符是\n。它在字符串中使用”。
我发现最简单易读的方法是使用“format”函数,使用nl作为新行名称,并将你想打印的字符串转换为你要打印的确切格式:
Python 2:
print("line1{nl}"
"line2{nl}"
"line3".format(nl="\n"))
Python 3:
nl = "\n"
print(f"line1{nl}"
f"line2{nl}"
f"line3")
这将输出:
line1
line2
line3
通过这种方式,它可以执行任务,并且还提供了代码的高可读性:)
值得注意的是,当你使用交互式Python shell或Jupyter Notebook检查字符串时,\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中,该语言会在平台的原生表示中为你编码换行符。这意味着在Windows上是\r\n,而在成熟的系统上只是\n。
即使在U*x系统上,以文本模式读取Windows行结束符的文件也会返回正确的文本结果,即在\n字符之前的任何\r字符都会被无声地删除。
如果需要完全控制文件中的字节,则可以使用二进制模式。然后,每个字节恰好对应一个字节,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'
各种等效方法
使用打印
默认情况下,打印已经追加了换行符!
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")打开文件。
推荐文章
- 将Pandas或Numpy Nan替换为None以用于MysqlDB
- 使用pandas对同一列进行多个聚合
- 使用Python解析HTML
- django MultiValueDictKeyError错误,我如何处理它
- 如何在for循环期间修改列表条目?
- 我如何在Django中创建一个鼻涕虫?
- 没有名为'django.core.urlresolvers'的模块
- 蟒蛇导出环境文件
- Django - makemigrations -未检测到任何更改
- SQLAlchemy:引擎、连接和会话差异
- 在Python Pandas中删除多个列中的所有重复行
- 更改pandas DataFrame中的特定列名
- 将Pandas多索引转换为列
- 熊猫在每组中获得最高的n个记录
- 熊猫数据帧得到每组的第一行