【问题标题】:How do I specify new lines on Python, when writing on files?在写入文件时,如何在 Python 上指定新行?
【发布时间】:2012-07-14 21:23:45
【问题描述】:

与 Java(在字符串中)相比,您会执行类似 "First Line\r\nSecond Line" 的操作。

那么,为了将多行写入常规文件,您将如何在 Python 中执行此操作?

【问题讨论】:

  • 你试过什么?它奏效了吗? (我猜不是,或者你不会问。)发生了什么?
  • 我只是想知道是否有正确和错误的方法,但我还没有尝试过。
  • 您确实意识到 Python 的 print 的工作方式与 Java 中的 System.out.println 类似,并且会在文本后自动添加换行符,对吧?
  • Python 中的print 语句也可用于写入文件(Python 2.x 和 Python 3.x 之间的细节有所不同,因此请查看您的版本的参考文档)。 print in Python 2.x - print in Python 3.x
  • 这里是交易:Python 做普通的 vanilla IO 成功地翻译了 '\n'。但是,如果您想真正找到平台的实际 lineep 怎么办?然后你需要 os.linesep。

标签: python line-breaks file-writing


【解决方案1】:

这取决于你想要的正确程度。 \n 通常会完成这项工作。如果你真的想把它弄对,你可以在os package 中查找换行符。 (实际上叫linesep。)

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

【讨论】:

  • 来自您提供的链接“在写入以文本模式打开的文件时,不要使用 os.linesep 作为行终止符(默认);在所有平台上使用单个 '\n'。”那么您所说的“正确”是什么意思?他们和您发表评论的原因是什么?
  • @Yasen:在 Windows 上,换行符序列是 "\r\n"。这意味着os.linesep 将是"\r\n"。当您以文本模式写入文件时,它会在写入时进行换行翻译;也就是说,输出中的每个"\n" 都将转换为结果文件中的"\r\n"。如果您正在编写的文本已经包含"\r\n" 序列,您可以看到这是一个问题:结果将是每行末尾的"\r\r\n"。我假设,至少:我还没有真正尝试过。
  • 可能是时候修复答案并删除错误的os.linesep 提案了,不是吗?这不会是一部大戏,我相信作者的自尊心不会受到太大影响
  • 你不知道我的骄傲。但更严重的是,我认为注意到linesep 存在并且存在这样您可以找出系统行分隔符是什么是有用的。
  • @ZAB 并非所有字符串都以文本模式写入文件。 linesep 仍然有用。
【解决方案2】:

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

例子:

    print('First line \n Second line') 

\n 是换行符。

这将产生结果:

First line
 Second line

如果您使用 Python 2,则不要在 print 函数上使用括号。

【讨论】:

  • 只是作为一个建议,如果我们在 \n 之后没有给出“空白”,我们不会在第二行得到一个空格缩进。我的意思是:打印'第一行\n第二行'
  • 感谢您指出在字符串中使用转义的“\n”字符!对于像我这样的 Python 新手来说可能并不明显
  • @all/anyone/ManojKumar a=1; b=2;打印(a,"\n",b); o / p:1 2(2在新行上,有一个空格缩进它看起来不正确,但假设1和2在不同的行上,2上有一个空格缩进)在这种情况下,我将如何删除白色空格(一个space indent) 在 2 之前,并将缩进 1。注意:我们不会使用 2 打印语句,1 和 2 将在单独的(新)行上。
【解决方案3】:

您可以单独写入新行或在单个字符串中写入,这更容易。

示例 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

【讨论】:

  • 我认为您的输出在技术上不正确。第二行和第三行应在其第一个字符的左侧打印一个空格。另一种解决方案是从 line 变量中删除这两个空格。
  • 无论如何,示例二中的代码不会产生您所显示的确切输出。
【解决方案4】:

独立于平台的断线:Linux、windows & IOS

import os
keyword = 'physical'+ os.linesep + 'distancing'
print(keyword)

输出:

physical
distancing

【讨论】:

  • 感谢您返回并将其更改为 covid 的“物理距离”
【解决方案5】:

编辑:我现在年纪大了,也更聪明了。这是一个更具可读性的解决方案,即使您不在顶级缩进(例如在函数定义中)也能正常工作。

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\
")

每行末尾的 \ 转义新行(这会导致错误)。

【讨论】:

  • 您的内括号,因此不需要转义行。只需结束字符串,移至新行,然后开始新行。不会有任何额外的新线路,你也不需要逃跑。此外,即使您确实执行了上述操作,换行符和转义符也会相互抵消。
  • @user144153 但是,至少,OP 的意图适用于print('...'),不是吗?也是括号,但你应该使用\n和`\`。
  • 即使在对print 的调用中,括号的处理方式也是相同的。如果您结束字符串文字并在新行上开始第二个文字,则不需要换行。
  • @user144153 你测试了吗?我只是将它粘贴到没有反斜杠的终端中,它会产生SyntaxError: EOL while scanning string literal
  • @fredcallaway 是的,我已经测试过了,可以确认它有效。您必须确保在下一行开始新的字符串文字之前结束字符串文字。
【解决方案6】:

最简单的解决方案

如果你只调用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()

【讨论】:

  • 由于提到了多行字符串,这应该被评为更高
【解决方案7】:

在 Python 中,您可以只使用换行符,即\n

【讨论】:

  • @maazza: 不是关于写作的问题吗?
【解决方案8】:

正如其他答案中提到的:“换行符是 \n。它在字符串中使用”。

我发现最简单易读的方法是使用“格式”函数,使用 nl 作为新行的名称,并将要打印的字符串分解为要打印的确切格式:

python2:

print("line1{nl}"
      "line2{nl}"
      "line3".format(nl="\n"))

python3:

nl = "\n"
print(f"line1{nl}"
      f"line2{nl}"
      f"line3")

这将输出:

line1
line2
line3

这样它可以执行任务,并且代码的可读性也很高:)

【讨论】:

    【解决方案9】:

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

    【讨论】:

    • \r 是回车,当你得到新行的系统属性时,它显示为\r\n
    • @SmartLemon:在 Windows 上可能是这样,但在大多数其他系统上,\n 是唯一的换行符。
    • @Jean-MichaëlCelerier:在 Mac OS X 之前确实如此。Mac OS X 使用 \n
    • 好吧,我把我的评论删了,那真的没用了。对不起!
    【解决方案10】:

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

    【讨论】:

    • 因为 Python 和 Java 受到了 C 的影响,并且从这种语言中得到了它们。 For more info.
    【解决方案11】:

    \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.....
    

    【讨论】:

      【解决方案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!
      

      【讨论】:

        【解决方案13】:

        在 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'
        

        【讨论】:

          【解决方案14】:

          \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()
          

          【讨论】:

            【解决方案15】:
            "{}\n{}\n{}".format(
                "line1",
                "line2",
                "line3"
            )
            

            个人比较喜欢这种格式

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2015-05-24
              • 1970-01-01
              • 2022-11-13
              • 1970-01-01
              • 1970-01-01
              • 2018-12-08
              • 1970-01-01
              相关资源
              最近更新 更多