Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/EmptyTag/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在编写文件时,如何在Python上指定新行?_Python_Line Breaks_File Writing - Fatal编程技术网

在编写文件时,如何在Python上指定新行?

在编写文件时,如何在Python上指定新行?,python,line-breaks,file-writing,Python,Line Breaks,File Writing,与Java(以字符串形式)相比,您可以执行类似于的“第一行\r\n第二行” 那么,在Python中,为了将多行写入一个常规文件,您将如何做到这一点呢?与'\n'的方法相同,尽管您可能不需要'\r'。在Java版本中使用它有什么原因吗?如果您确实需要/想要它,您也可以在Python中以同样的方式使用它。在Python中,您可以只使用新行字符,即\n这取决于您希望的正确程度\n通常会执行此任务。如果你真的想把它做好,你可以在列表中查找换行符。(它实际上被称为linesep) 注意:使用Python

与Java(以字符串形式)相比,您可以执行类似于
的“第一行\r\n第二行”


那么,在Python中,为了将多行写入一个常规文件,您将如何做到这一点呢?

'\n'
的方法相同,尽管您可能不需要
'\r'
。在Java版本中使用它有什么原因吗?如果您确实需要/想要它,您也可以在Python中以同样的方式使用它。

在Python中,您可以只使用新行字符,即
\n
这取决于您希望的正确程度<代码>\n通常会执行此任务。如果你真的想把它做好,你可以在列表中查找换行符。(它实际上被称为
linesep


注意:使用Python API写入文件时,不要使用
os.linesep
。只需使用
\n
;Python会自动将其转换为适合您平台的换行符。

大多数Java字符串文本中的转义字符在Python中也有效,例如“\r”和“\n”。

换行符是
\n
。它在字符串中使用

例如:

    print('First line \n Second line') 
其中
\n
是换行符

这将产生以下结果:

First line
 Second line

如果使用Python2,则不会在print函数中使用括号。

可以单独写入新行,也可以在单个字符串中写入,这样更容易

例1 输入 您可以单独写入“\n”:

file.write(line1)
file.write("\n")
file.write(line2)
file.write("\n")
file.write(line3)
file.write("\n")
输出 例2 输入 正如其他人在前面的回答中指出的,请将\n放置在字符串中的相关点:

line = "hello how are you\nI am testing the new line escape sequence\nthis seems to work"

file.write(line)
输出
编辑:我现在更老更聪明了。这里有一个更具可读性的解决方案,即使您不是顶级缩进(例如,在函数定义中),它也能正常工作

原始答案

如果您同时输入几行文本,我发现这是最可读的格式

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
您可以通过管道将输出传输到如下文件(考虑您的示例):

它不仅与操作系统无关(甚至不必使用
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()

\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分隔字符串的行。在下面的示例中,我一直在循环中写入记录。每个记录由
\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

导入操作系统
关键字='physical'+os.linesep+'distancing'
打印(关键字)
输出:

物理
疏远

如其他答案中所述:“新行字符是\n。它在字符串中使用”

我发现最简单易读的方法是使用“format”函数,使用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

通过这种方式,它可以执行任务,还可以提供代码的高可读性:)

值得注意的是,当您使用交互式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!

在Python3中,该语言负责在平台的本机表示中为您编码换行符。这意味着Windows上的
\r\n
,而成熟系统上的
\n

即使在U*x系统上,在文本模式下读取带有Windows行结尾的文件也会返回正确的文本结果,即在默认删除
\n
字符之前的任何
\r
字符

如果需要对文件中的字节进行完全控制,可以使用二进制模式。然后每个字节恰好对应一个字节,Python不执行任何转换

>#使用二进制模式编写具有不同行尾的文件以实现完全控制
>>>将open('/tmp/demo.txt',wb')作为wf:
...     wf.write(b'DOS行\r\n')
...     wf.write(b'U*x行\n')
...     wf.write(b‘无行’)
10
9
7.
>>>#以文本形式读取文件
>>>以open('/tmp/demo.txt',r')作为文本:
...     对于文本中的行:
...         打印(行,结束=“”)
DOS线
U*x线
没线
>>>#或者更明显
>>>以open('/tmp/demo.txt',r')作为文本:
...     对于文本中的行:
...         打印(报告(行))
'DOS行\n'
'U*x行\n'
“没有线路”
>>>#回到字节!
>>>将open('/tmp/demo.txt',rb')作为二进制文件:
...     对于二进制的行:
...         打印(行)
b'DOS行\r\n'
b'U*x行\n'
b‘不排队’
>>>#以二进制打开,但转换回文本
>>>将open('/tmp/demo.txt',rb')作为二进制文件:
...     对于二进制的行:
...         打印(行解码('utf-8'),结束=“”)
DOS线
U*x线
没线
>>>#或者更详细地说,使用repr()
>>>将open('/tmp/demo.txt',rb')作为二进制文件:
...     对于二进制的行:
...         打印(报告(行解码('utf-8'))
'DOS行\r\n'
'U*x行\n'
“没有线路”

您尝试过什么?它起作用了吗?(我想不会,否则你就不会问了。)
print("line1{nl}"
      "line2{nl}"
      "line3".format(nl="\n"))
nl = "\n"
print(f"line1{nl}"
      f"line2{nl}"
      f"line3")
line1
line2
line3
>>> 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!