gpt4 book ai didi

python - 将新行添加到输出文件python

转载 作者:太空宇宙 更新时间:2023-11-04 06:15:00 24 4
gpt4 key购买 nike

您好,我想将换行符写入输出文件,所以这是我的代码:

a=['\n:001000', '\r:10111', ' :000', '!:01101111101', '":0010011', "':0010010110", '(:00100101111110110', '):00100101111110111', ',:101100', '-:1011011011', '.:0100100', '0:011011111001101', '1:0110111110010', '2:1011011000111', '3:011011111001110']

text_file = open("Output.txt", "wb")
for t in a:
text_file.write(t+" ")

但我的输出不是我所期望的:

:001000  :10111   :000  !:01101111101  ":0010011  ':0010010110  (:00100101111110110  ):00100101111110111  ,:101100  -:1011011011  .:0100100  0:011011111001101  1:0110111110010  2:1011011000111  3:011011111001110  

有谁知道如何将换行符实际写入输出???

我想要像这样的东西:\n:001000\r:10111 等等

最佳答案

你正在打印那些字符,只要看看 repr

>>> a=['\n:001000 ', '\r:10111 ', ' :000 ', '!:01101111101 ', '":0010011 ', "':0010010110 ", '(:00100101111110110 ', '):00100101111110111 ', ',:101100 ', '-:1011011011 ', '.:0100100 ', '0:011011111001101 ', '1:0110111110010 ', '2:1011011000111 ', '3:011011111001110 ']
>>> with open("Output.txt", "wb") as f:
for t in a:
f.write(t + " ")


>>> with open("Output.txt", "rb") as f:
print repr(f.read()) # representation


'\n:001000 \r:10111 :000 !:01101111101 ":0010011 \':0010010110 (:00100101111110110 ):00100101111110111 ,:101100 -:1011011011 .:0100100 0:011011111001101 1:0110111110010 2:1011011000111 3:011011111001110 '

或者您可能要求转义这些字符以原始打印它们:

>>> with open("Output.txt", "wb") as f:
for t in a:
f.write((t + " ").encode('string_escape'))


>>> with open("Output.txt", "rb") as f:
print f.read()


\n:001000 \r:10111 :000 !:01101111101 ":0010011 \':0010010110 (:00100101111110110 ):00100101111110111 ,:101100 -:1011011011 .:0100100 0:011011111001101 1:0110111110010 2:1011011000111 3:011011111001110

关于python - 将新行添加到输出文件python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16314888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com