關於python open函數緩衝區的問題

open函數原型
open(name[, mode[, buffering]])
關於第三個參數buffering,文檔中的解釋是

The optional buffering argument specifies the file’s desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size. A negative buffering means to use the system default, which is usually line buffered for tty devices and fully buffered for other files. If omitted, the system default is used.

可以看到:

  1. 若buffering爲0或False,沒有緩衝區;

    f = open(r’D:\code\py\opentest’, ‘w’, False),
    f.write(‘望水至極’)
    去opentest文件查看,字符串已被寫入文件。

  2. 若爲1或True有緩衝區;
    f = open(r’D:\code\py\opentest’, ‘w’, True)
    f.write(‘望水至極’)
    有緩衝區,不過文檔時說“1 means line buffered”行緩衝?不理解什麼意思,不過使用上感覺和使用默認緩衝區一樣;
    若緩衝區滿了則自動寫入文件opentest中,否則需要f.flush()或f.close(),才能寫入opentest文件;

  3. 若爲其他正數則表示緩衝區大小;
    f = open(r’D:\code\py\opentest’, ‘w’, 20)
    有緩衝區,緩衝區大小20字節
    當寫入字符串少於20字節時,先寫入緩衝區,需要flush或close(),才能寫入opentest文件;
    當字符串不少於20字節時,先寫入緩衝區,若緩衝區滿了,則自動寫入opentest文件,依次類推,最後緩衝區中的內容需f.flush或f.close(),才能寫入opentest文件;

  4. 若爲負數,則使用默認緩衝區大小;
    f = open(r’D:\code\py\opentest’, ‘w’, -1)
    f.write(‘望水至極’)
    先寫入緩衝區,若緩衝區滿了則自動寫入文件opentest中,否則需要f.flush()或f.close()才能寫入文件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章