问题:在写入文件时,如何在Python中指定换行符?
与Java(以字符串形式)相比,您可以执行"First Line\r\nSecond Line"
。
那么,为了在常规文件中写多行,您将如何在Python中执行此操作?
In comparison to Java (in a string), you would do something like "First Line\r\nSecond Line"
.
So how would you do that in Python, for purposes of writing multiple lines to a regular file?
回答 0
这取决于您想做的正确程度。\n
通常会做的工作。如果您确实想解决问题,请在os
包中查找换行符。(实际上称为linesep
。)
注意:使用Python API写入文件时,请勿使用os.linesep
。随便用\n
; Python会自动将其转换为适合您平台的换行符。
It depends on how correct you want to be. \n
will usually do the job. If you really want to get it right, you look up the newline character in the os
package. (It’s actually called linesep
.)
Note: when writing to files using the Python API, do not use the os.linesep
. Just use \n
; Python automatically translates that to the proper newline character for your platform.
回答 1
新行字符为\n
。它在字符串内使用。
例:
print('First line \n Second line')
\n
换行符在哪里。
这将产生结果:
First line
Second line
如果使用Python 2,则不要在print函数上使用括号。
The new line character is \n
. It is used inside a string.
Example:
print('First line \n Second line')
where \n
is the newline character.
This would yield the result:
First line
Second line
If you use Python 2, you do not use the parentheses on the print function.
回答 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
You can either write in the new lines separately or within a single string, which is easier.
Example 1
Input
line1 = "hello how are you"
line2 = "I am testing the new line escape sequence"
line3 = "this seems to work"
You can write the ‘\n’ separately:
file.write(line1)
file.write("\n")
file.write(line2)
file.write("\n")
file.write(line3)
file.write("\n")
Output
hello how are you
I am testing the new line escape sequence
this seems to work
Example 2
Input
As others have pointed out in the previous answers, place the \n at the relevant points in your string:
line = "hello how are you\nI am testing the new line escape sequence\nthis seems to work"
file.write(line)
Output
hello how are you
I am testing the new line escape sequence
this seems to work
回答 3
如果您一次输入多行文本,我发现这是最易读的格式。
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\
")
每行末尾的\将转义新行(这将导致错误)。
If you are entering several lines of text at once, I find this to be the most readable format.
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\
")
The \ at the end of each line escapes the new line (which would cause an error).
回答 4
In Python you can just use the new-line character, i.e. \n
回答 5
最简单的解决方案
如果仅print
不带任何参数的情况下调用,它将输出空白行。
print
您可以将输出通过管道传输到这样的文件中(考虑您的示例):
f = open('out.txt', 'w')
print 'First line' >> f
print >> f
print 'Second line' >> f
f.close()
它不仅与操作系统无关(甚至无需使用os
软件包),而且比放在\n
字符串中更具可读性。
说明
该print()
函数在字符串的末尾有一个可选的关键字参数,称为end
,默认为OS的换行符,例如。\n
。因此,当您打电话时print('hello')
,Python实际上正在打印'hello' + '\n'
。这意味着当您print
不带任何参数调用时,它实际上是print '' + '\n'
,这导致换行符。
另类
使用多行字符串。
s = """First line
Second line
Third line"""
f = open('out.txt', 'w')
print s >> f
f.close()
Simplest solution
If you only call print
without any arguments, it will output a blank line.
print
You can pipe the output to a file like this (considering your example):
f = open('out.txt', 'w')
print 'First line' >> f
print >> f
print 'Second line' >> f
f.close()
Not only is it OS-agnostic (without even having to use the os
package), it’s also more readable than putting \n
within strings.
Explanation
The print()
function has an optional keyword argument for the end of the string, called end
, which defaults to the OS’s newline character, for eg. \n
. So, when you’re calling print('hello')
, Python is actually printing 'hello' + '\n'
. Which means that when you’re calling just print
without any arguments, it’s actually printing '' + '\n'
, which results in a newline.
Alternative
Use multi-line strings.
s = """First line
Second line
Third line"""
f = open('out.txt', 'w')
print s >> f
f.close()
回答 6
独立于平台的断线器:Linux,Windows和IOS
import os
keyword = 'physical'+ os.linesep + 'distancing'
print(keyword)
输出:
physical
distancing
Platform independent line breaker: Linux,windows & IOS
import os
keyword = 'physical'+ os.linesep + 'distancing'
print(keyword)
Output:
physical
distancing
回答 7
与相同的方法'\n'
,尽管您可能不需要'\r'
。您是否有理由在Java版本中使用它?如果确实需要/想要它,您也可以在Python中以相同的方式使用它。
The same way with '\n'
, though you’d probably not need the '\r'
. Is there a reason you have it in your Java version? If you do need/want it, you can use it in the same way in Python too.
回答 8
\ 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.....
\n – simple newline character insertion works:
# 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.....
回答 9
Java字符串文字中的大多数转义字符在Python中也有效,例如“ \ r”和“ \ n”。
Most escape characters in string literals from Java are also valid in Python, such as “\r” and “\n”.
回答 10
如其他答案所述:“换行符为\ n。它在字符串内使用”。
我发现最简单易读的方法是使用“格式”功能,将nl用作新行的名称,然后将要打印的字符串分解为要打印的确切格式:
print("line1{nl}"
"line2{nl}"
"line3".format(nl="\n"))
将会输出:
line1
line2
line3
这样,它可以执行任务,并且还可以使代码具有较高的可读性:)
As mentioned in other answers: “The new line character is \n. It is used inside a string”.
I found the most simple and readable way is to use the “format” function, using nl as the name for a new line, and break the string you want to print to the exact format you going to print it:
python2:
print("line1{nl}"
"line2{nl}"
"line3".format(nl="\n"))
python3:
nl = "\n"
print(f"line1{nl}"
f"line2{nl}"
f"line3")
That will output:
line1
line2
line3
This way it performs the task, and also gives high readability of the code :)
回答 11
\ 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 separates the lines of a string. In the following example, I keep writing the records in a loop. Each record is separated by \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()
回答 12
值得注意的是,当您使用交互式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!
Worth noting that when you inspect a string using the interactive python shell or a Jupyter notebook, the \n
and other backslashed strings like \t
are rendered literally:
>>> 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!'
The newlines, tabs, and other special non-printed characters are rendered as whitespace only when printed, or written to a file:
>>> print('{}'.format(gotcha))
Here is some random message...
Additional content:
Yet even more great stuff!