cannot read ascii character 26?

前端 未结 2 1639
后悔当初
后悔当初 2020-12-21 06:28

I wrote a stream in a file in text mode.

# python code
f = open(\"somewhere in my computer\",\"w\")
f.write(\"Hello\\nWorld\")
f.write(chr(26)) # writing asc         


        
相关标签:
2条回答
  • This code words for me to open and read the file on Windows. Furthermore, using curses, you can get a "^" representation of any control characters that may be in your file.

    import curses.ascii
    
    filename = "myfile.txt"
    f = open(filename,"w")
    f.write("Hello\nWorld")
    f.write(chr(26)) # writing ascii character #26 to file 
    f.write("hhh")
    f.close()
    
    with open(filename,'r') as f:
        for line in f:
            line2 = [ curses.ascii.unctrl(c) if curses.ascii.iscntrl(c) else c for c in line]
            print("".join(line2))
    
    Gives output:
    Hello^J
    World^Zhhh
    
    0 讨论(0)
  • 2020-12-21 06:45

    The problem is because of the windows. 0x1A is Ctrl-Z, and DOS used that as an end-of-file marker. Python uses the Windows CRT function _wfopen, which implements the "Ctrl-Z is EOF" semantics. If your file wasn't an exact multiple of 128 bytes, you needed a way to mark the end of the text. This article implies that the selection of Ctrl-Z was based on an even older convention used by DEC.

    0 讨论(0)
提交回复
热议问题