问题
The docs for TextIOBase.tell, from which TextIOWrapper
inherits, state
Return the current stream position as an opaque number. The number does not usually represent a number of bytes in the underlying binary storage.
I am wondering, whether it will always return zero in the specific case that the file pointer is at the beginning of the file?
I wrote a small, non-exhaustive, script to check some obvious scenarios, which returned zero for each case:
import io
import os
rmodes = ['a', 'a+', 'r', 'r+']
wmodes = ['w', 'w+', 'a', 'a+', 'x', 'x+']
for m in wmodes:
with open('empty.txt', m) as f:
print(m, f.tell())
os.system('rm empty.txt')
for m in rmodes:
open('not-empty.txt', 'w').write('abc\n')
with open('non-empty.txt', m) as f:
f.seek(0, io.SEEK_SET)
print(m, f.tell())
if m == 'r':continue # avoid exception
with open('non-empty.txt', m) as f:
f.truncate()
print(m, f.tell())
I believe this code is used to generate the return value of tell
static PyObject *
textiowrapper_build_cookie(cookie_type *cookie)
{
unsigned char buffer[COOKIE_BUF_LEN];
memcpy(buffer + OFF_START_POS, &cookie->start_pos, sizeof(cookie->start_pos));
memcpy(buffer + OFF_DEC_FLAGS, &cookie->dec_flags, sizeof(cookie->dec_flags));
memcpy(buffer + OFF_BYTES_TO_FEED, &cookie->bytes_to_feed, sizeof(cookie->bytes_to_feed));
memcpy(buffer + OFF_CHARS_TO_SKIP, &cookie->chars_to_skip, sizeof(cookie->chars_to_skip));
memcpy(buffer + OFF_NEED_EOF, &cookie->need_eof, sizeof(cookie->need_eof));
return _PyLong_FromByteArray(buffer, sizeof(buffer),
PY_LITTLE_ENDIAN, 0);
}
Clearly it computes more than just the offset of the file pointer from the beginning of the file. But will this code always return zero at the beginning of a file? What might be the circumstances in which it would not?
I am
- aware that the behaviour is implementation-dependent and not guaranteed by the docs
- asking specifically about the behaviour in text files, not binary
- not asking "how do I know if I am at the beginning of a file in Python?"
- not asking for alternative means of obtaining the position of the file pointer
来源:https://stackoverflow.com/questions/61317588/will-textiowrapper-tell-reliably-return-zero-at-the-beginning-of-a-file