3
votes

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 ascii character #26 to file 
f.write("hhh")
f.close()

I cannot read bytes after ASCII character #26. I know i should open file with binary mode. Is ascii character #26 EOF character. As you know there is not such thing , e.i there is no EOF character. So what is problem? Is this an operating system dependent issue? (I try this in Microsoft windows).

2
Works for me (OSX). Post the code you're using to read it. - Kevin
f = open("somewhere in my computer","r") t = f.read() print len(t) # tells 11 and file is at end - Hesam Qodsi
I think in unix like systems there is no difference between text and binary files. - Hesam Qodsi
"I know I should open file with binary mode." So do it. In DOS/Windows, files opened in text mode interpret ASCII 26 (control-Z) as an end of file marker, even though there isn't really such thing as an end of file character in the ASCII standard. It's a OS-specific quirk - almost all other modern operating systems do not do this (although there may still be others, so I won't state that definitively)... - twalberg
@HesamQodsi On the other hand, I would argue that when you develop an application, it is your job to consider every detail of how that application will interact with whatever environment (operating system, libraries, frameworks, APIs, etc.) it will find itself running in... That would include how to properly open and parse files on that particular environment, as well as a great deal of other details... - twalberg

2 Answers

3
votes

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.

1
votes

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