Skip to main content
 首页 » 编程设计

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

2025年05月04日8开发

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

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