如何在字符串中指定新行以便将多行写入文件?
- 2025-01-21 09:01:00
- admin 原创
- 76
问题描述:
如何在 Python 中的字符串中指示换行符,以便可以将多行写入文本文件?
解决方案 1:
这取决于你想要的正确程度。通常可以完成工作。如果你真的想做对,你可以在包`中查找换行符。(它实际上叫做。)
os`linesep
注意:使用 Python API 写入文件时,请勿使用os.linesep
。只需使用`
`;Python 会自动将其转换为适合您平台的换行符。
解决方案 2:
换行符是`
`。它在字符串内部使用。
例子:
print('First line
Second line')
`
`换行符在哪里。
这将产生以下结果:
First line
Second line
如果您使用 Python 2,则不要在打印函数上使用括号。
解决方案 3:
独立于平台的换行符:Linux、Windows 和 iOS
import os
keyword = 'physical'+ os.linesep + 'distancing'
print(keyword)
输出:
physical
distancing
解决方案 4:
您可以单独在新行中写入,也可以在单个字符串中写入,这样更简单。
示例 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("
")
file.write(line2)
file.write("
")
file.write(line3)
file.write("
")
输出
hello how are you
I am testing the new line escape sequence
this seems to work
示例 2
输入
正如其他人在前面的答案中指出的那样,将 \n 放在字符串中的相关点:
line = "hello how are you
I am testing the new line escape sequence
this seems to work"
file.write(line)
输出
hello how are you
I am testing the new line escape sequence
this seems to work
解决方案 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.
"""))
解决方案 6:
最简单的解决方案
如果仅仅调用print
而不使用任何参数,它将输出一个空白行。
print
您可以将输出通过管道传输到这样的文件(考虑您的示例):
f = open('out.txt', 'w')
print 'First line' >> f
print >> f
print 'Second line' >> f
f.close()
它不仅与操作系统无关(甚至无需使用os
包),而且比放入`
`字符串中更具可读性。
解释
该print()
函数有一个可选的关键字参数,用于表示字符串的结尾,称为end
,默认为操作系统的换行符,例如 。`因此,当您调用 时
print('hello'),Python 实际上正在打印
'hello' + '
'。这意味着当您调用 just
print而不使用任何参数时,它实际上是在打印
'' + '
'`,从而产生换行符。
选择
使用多行字符串。
s = """First line
Second line
Third line"""
f = open('out.txt', 'w')
print s >> f
f.close()
解决方案 7:
在 Python 中,你可以使用换行符,即`
`
解决方案 8:
正如其他答案中提到的:“换行符是 \n。它在字符串内部使用”。
我发现最简单、最易读的方法是使用“格式”函数,使用 nl 作为新行的名称,并将要打印的字符串分解为要打印的确切格式:
Python 2:
print("line1{nl}"
"line2{nl}"
"line3".format(nl="
"))
Python 3:
nl = "
"
print(f"line1{nl}"
f"line2{nl}"
f"line3")
这将输出:
line1
line2
line3
这样它就可以完成任务,并且还能提高代码的可读性:)
解决方案 9:
与 的方法相同`'
',尽管你可能不需要
'
'`。 你在 Java 版本中使用它有什么原因吗? 如果你确实需要/想要它,你也可以在 Python 中以相同的方式使用它。
解决方案 10:
值得注意的是,当你使用交互式 Python shell 或Jupyter Notebook检查字符串时,`和其他反斜杠字符串(如)将按**字面意思**
`呈现:
>>> gotcha = 'Here is some random message...'
>>> gotcha += '
Additional content:
{}'.format('Yet even more great stuff!')
>>> gotcha
'Here is some random message...
Additional content:
Yet even more great stuff!'
换行符、制表符和其他特殊的非打印字符仅在打印或写入文件时才呈现为空格:
>>> print('{}'.format(gotcha))
Here is some random message...
Additional content:
Yet even more great stuff!
解决方案 11:
Java 字符串文字中的大多数转义字符在 Python 中也有效,例如“\r”和“\n”。
解决方案 12:
\n-简单的换行符插入工作:
# Here's the test example - string with newline char:
In [36]: test_line = "Hi!!!
testing first line..
testing second line..
and third line....."
输出:
In [37]: print(test_line)
Hi!!!
testing first line..
testing second line..
and third line.....
解决方案 13:
在 Python 3 中,语言会按照平台的原生表示为您编码换行符。这意味着`在 Windows 上,以及
`在成熟的系统上。
即使在 U*x 系统上,以文本模式读取带有 Windows 行尾的文件也会返回正确的文本结果,即,字符`之前的任何字符
`都会被默默删除。
如果需要完全控制文件中的字节,可以使用二进制模式。这样每个字节都精确对应一个字节,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
')
... wf.write(b'U*x line
')
... 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
'
'U*x line
'
'no line'
>>> # Back to bytes!
>>> with open('/tmp/demo.txt', 'rb') as binary:
... for line in binary:
... print(line)
b'DOS line
'
b'U*x line
'
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
'
'U*x line
'
'no line'
解决方案 14:
使用:
"{}
{}
{}".format(
"line1",
"line2",
"line3"
)
我个人更喜欢这种格式。
解决方案 15:
\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) + '
')
f.close()
解决方案 16:
各种等效方法
使用print
print
已经默认附加了一个换行符!
with open("out.txt", "w") as f:
print("First", file=f)
print("Second", file=f)
等价地:
with open("out.txt", "w") as f:
print("First
Second", file=f)
如果print
不想自动添加换行符,请使用sep=""
(因为`sep="
"`是默认值):
with open("out.txt", "w") as f:
print("First
Second
", sep="", file=f)
使用f.write
对于以文本模式打开的文件:
with open("out.txt", "w") as f:
f.write("First
Second
")
对于以二进制模式打开的文件,文件将不会自动转换为`特定于平台的行终止符。要强制使用当前平台的换行符,请使用
os.linesep而不是
`:
with open("out.txt", "wb") as f:
f.write("First" + os.linesep)
f.write("Second" + os.linesep)
输出文件
视觉上:
First
Second
在 Linux 上,换行符将由以下字符分隔`
`:
First
Second
在 Windows 上,换行符将由以下字符分隔`
`:
First
Second
为了避免对以文本模式打开的文件自动翻译为`,
请使用 打开文件
open("out.txt", "w", newline="
")`。