python - 如何在Python中创建一个指定大小的文件?

标签 python python-3.x file

我正在处理的文件格式在文件前面有一个 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/

相关文章:

python - 如何转换这个数据框以获得这个json结构?

python - 禁用 "\"字符 Python 2.7 的自动加倍 - re2 错误

python - 在 Docker 容器中找不到模块

python-3.x - 如何使用python函数迭代从另一个函数接收的文件

file - Felix 文件安装 OSGi : How to automatically load a bundle (Configuration and how it works)?

javascript - 在 jquery 中获取输入类型文件的 event.result

Python多处理器编程

python - 如何在组内逐条查找唯一值?

python - 如何在 python 3.7 中加密和解密字符串?

C++ : Read random line from text file