我正在处理的文件格式在文件前面有一个 8192 字节的 header 。为了创建一个空文件,我需要一个清零的 header (文件格式规范不受我的控制)。我当前的解决方案是这样的:
with open(fileName, mode='w+b') as f:
for i in range(8192):
f.write(b'\x00')
是否有更好(更有效)的方法来做到这一点?
最佳答案
使用bytes
内置:
with open(filename, 'wb') as f:
f.write(bytes(8192))
来自文档:
The optional source parameter can be used to initialize the array in a few different ways:
- If it is an integer, the array will have that size and will be initialized with null bytes.
关于python - 如何在Python中创建一个指定大小的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64134951/