用于
fileobject.seek()从末尾寻找1个位置,然后用于
file.truncate()删除文件的其余部分:
import oswith open(filename, 'rb+') as filehandle: filehandle.seek(-1, os.SEEK_END) filehandle.truncate()
这对于单字节编码工作正常。如果您使用多字节编码(例如UTF-16或UTF-32),则需要从头开始查找足够的字节以说明单个代码点。
对于可变字节编码,如果您完全可以使用此技术,则取决于编解码器。对于UTF-8,您需要找到第一个字节(从结尾开始)
bytevalue & 0xC0 !=0x80为true,然后从该点开始截断。这样可以确保您不会在多字节UTF-8代码点的中间截断:
with open(filename, 'rb+') as filehandle: # move to end, then scan forward until a non-continuation byte is found filehandle.seek(-1, os.SEEK_END) while filehandle.read(1) & 0xC0 == 0x80: # we just read 1 byte, which moved the file position forward, # skip back 2 bytes to move to the byte before the current. filehandle.seek(-2, os.SEEK_CUR) # last read byte is our truncation point, move back to it. filehandle.seek(-1, os.SEEK_CUR) filehandle.truncate()
请注意,UTF-8是ASCII的超集,因此以上内容也适用于ASCII编码的文件。



