我目前正在用 Raspberry Pi 创建一个数据记录功能,我不确定我是否发现了一个小错误。我使用的代码如下:
import sys, time, os
_File = 'TemperatureData1.csv'
_newDir = '/home/pi/Documents/Temperature Data Logs'
_directoryList = os.listdir(_newDir)
os.chdir(_newDir)
# Here I am specifying the file, that I want to write to it, and that
# I want to use a buffer of 5kb
output = open(_File, 'w', 5000)
try:
while (1):
output.write('hi\n')
time.sleep(0.01)
except KeyboardInterrupt:
print('Keyboard has been pressed')
output.close()
sys.exit(1)
我发现,当我定期查看创建的文件属性时,文件大小会根据默认缓冲区设置 8192 字节增加,而不是我指定的 5kb。但是,当我在 Python 2.7.13 中运行完全相同的程序时,缓冲区大小会按要求更改为 5kb。
我想知道是否还有其他人遇到过这种情况并对让程序在 Python 3.6.3 上运行的解决方案有任何想法?提前致谢。我可以在 python 2.7.13 上解决这个问题,这是我纯粹的好奇心导致我发布这个问题。
请您参考如下方法:
版本 2 中 Python 对 open 的定义就是您正在使用的:
open(name[, mode[, buffering]])
在 Python 3 中,open 命令有点不同,buffering 不是一个位置整数,而是一个关键字 arg:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
docs有以下注意事项:
bufferingis an optional integer used to set the buffering policy. Pass0to switch buffering off (only allowed in binary mode),1to select line buffering (only usable in text mode), and an integer >1to indicate the size in bytes of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows:Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device’s “block size” and falling back on io.DEFAULT_BUFFER_SIZE. On many systems, the buffer will typically be 4096 or 8192 bytes long. “Interactive” text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files.
那个特殊的 8192 数字就是 2^13。
我建议尝试 buffering=5000。
