classification
Title: The return of truncate(size=None) (file io) is unexpected
Type: behavior Stage: resolved
Components: IO Versions: Python 3.5
process
Status: closed Resolution: duplicate
Dependencies: Superseder: File truncate() not defaulting to current position as documented
View: 26158
Assigned To: Nosy List: liugang93, martin.panter
Priority: normal Keywords:

Created on 2018-11-23 19:35 by liugang93, last changed 2018-11-24 01:11 by martin.panter. This issue is now closed.

Messages (3)
msg330357 - (view) Author: liugang (liugang93) Date: 2018-11-23 19:35
-- run in Windows 10

1 - 
f = open('test', "w+")
f.write('xxx\nyyy\nzzz')

f.seek(0)

f.readline()
print(f.tell())  # output 5 (xxx\r\n)

x = f.truncate()
print(x)  # output 13 (xxx\r\nyyy\r\nzzz), why it is 13, not 5?

2 - 
f = open('test', "w+")
f.write('xxx\nyyy\nzzz')

f.seek(0)

f.readline()
print(f.tell())  # output 5 (xxx\r\n)

f.seek(f.tell())

x = f.truncate()
print(x)  # output 5
msg330358 - (view) Author: liugang (liugang93) Date: 2018-11-23 19:44
# Run in Windows 10

# Code snippet 1
f = open('test', "w+")
f.write('xxx\nyyy\nzzz')

f.seek(0)

f.readline()
print(f.tell())  # 5

x = f.truncate()
print(x)  # 13 - why it is 13, not 5?


# Code snippet 2
f = open('test', "w+")
f.write('xxx\nyyy\nzzz')

f.seek(0)

f.readline()
print(f.tell())  # 5

f.seek(f.tell())

x = f.truncate()
print(x)  # 5
msg330368 - (view) Author: Martin Panter (martin.panter) * (Python committer) Date: 2018-11-24 01:11
This is the same as Issue 26158. Truncating text files is not clearly documented for a start, and truncating after reading doesn’t seem to be considered much in the implementations.

Your question is answered at <https://bugs.python.org/issue26158#msg258619>. Your code calls the C implementation of “io.TextIOWrapper.truncate”. This implementation does not consider that there are 8 unread bytes in a buffer, so it truncates the file at the end of the buffer (5 read + 8 unread = 13 bytes).
History
Date User Action Args
2018-11-24 01:11:07martin.pantersetstatus: open -> closed

superseder: File truncate() not defaulting to current position as documented

nosy: + martin.panter
messages: + msg330368
resolution: duplicate
stage: resolved
2018-11-23 19:44:37liugang93setmessages: + msg330358
2018-11-23 19:35:08liugang93create