第5章P109のtruncateについて。
#/usr/bin/env #-*- encoding: utf-8 -*- import os def pythonic(): path = "./p109_truncate.txt" file = open(path, 'w', encoding='utf-8') file.write("abc") # write "abc" and offset move to 3 is end of file. print(file.tell()) # 3 # truncate padding 0. but offset won't move to end of file. file.truncate(100) # truncate don't move file offset print(file.tell()) # 3 # seek to end of file file.seek(0, os.SEEK_END) print(file.tell()) # 100 file.close() def unix(): path = "./p109_truncate.txt" os.truncate(path, 200) if __name__ == '__main__': pythonic() unix()
truncateは、ファイルを拡張してくれる。pythonicの方では、openで開いたファイルに対してtruncateを呼び出してるが、たぶんこっちはftruncateのファイルディスクリプタを使う方なんだと思う。Cのtruncateは、unixメソッドの方で示したos.truncateみたいにpathからファイルを拡張できるもの。os.ftruncateみたいにファイルディスクリプタを用いる方がpythonicメソッドで示したものだと思う。