4

I noticed a strange behavior of Python file handlers, when created in append mode. In the following example, ofh.tell() returns 0 the first time i use it in append mode.

ofh = open("test.txt","wb")
print ofh.tell() # output: 0
ofh.write("asdf")
print ofh.tell() # output: 4
ofh.close()

ofh = open("test.txt","ab")
print ofh.tell() # output: 0
ofh.seek(0,2) # seek to end of file
print ofh.tell() # output: 4

For some safety checks, i need it to return the "actual" position (4) in this case.

  1. Is manually seeking to the end of the file the way to go?
  2. Is there any good reason for the observed behavior? Returning a position different from where data will be written doesn't seem like a good idea.

I am using Python 2.7.10 and Windows 7 64bit.

3
  • For what it's worth, this appears to be part of the POSIX spec: "O_APPEND If set, the file offset shall be set to the end of the file prior to each write." No rationale is given in the spec for this behavior, either. Commented Jul 28, 2015 at 15:40
  • @chepner: OP is on Windows. Commented Jul 28, 2015 at 15:40
  • Oh, good point. Also just noticed that in Unix, the file pointer is moved to the end of the file immediately. Commented Jul 28, 2015 at 15:42

1 Answer 1

3

Under Python 2, append mode means every write goes to the end of the file. The file pointer might really start at zero, but that doesn't matter because it will seek to the end every time you write.

Note that seek() and tell() are largely useless in append mode, since the former will always be overridden by the implicit seek-to-end. If you need to append to the file without this behavior, open it in r+b mode and then manually seek to the end of the file.

Sign up to request clarification or add additional context in comments.

3 Comments

I would not rely on that ! Doc just says that on some Unix systems means that all writes append to the end of the file regardless of the current seek position. My understanding is that if you never seek, write will be appended to end of file, on any system. But if you use seek, following writes may be appended to end of file if you are on a Unix system implementing that feature ...
@SergeBallesta: The docs seem to contradict themselves on this point; the page I linked to does not hedge about different systems, but the open() docs do. I would agree that seeking an append-mode file is probably a Bad Idea anyway.
Works for me, and the seek() and tell() functions seem to be defined more clearly for this mode. Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.