关于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()才能写入文件

关于默认缓冲区大小究竟多大、行缓冲什么意思,本人暂时不知,希望了解的朋友可以指出,谢谢。

Thanks for your seeing!

猜你喜欢

转载自blog.csdn.net/u011878795/article/details/52194644
今日推荐