在python中创建特定大小的文件 [英] create file of particular size in python
问题描述
我想创建一个特定大小的文件(例如1GiB). 内容并不重要,因为我会在其中填充内容.
I want to create a file of particular size (say, 1GiB). The content is not important since I will fill stuff into it.
我正在做的是:
f = open("E:\\sample", "wb")
size = 1073741824 # bytes in 1 GiB
f.write("\0" * size)
但这需要很长时间才能完成.我花了大约1分钟的时间. 可以做些什么来改善这一点?
But this takes too long to finish. It spends me roughly 1 minute. What can be done to improve this?
推荐答案
警告该解决方案提供的结果可能出乎您的意料.参见UPD ...
WARNING This solution gives the result that you might not expect. See UPD ...
1创建新文件.
2尝试将大小限制为1个字节.
2 seek to size-1 byte.
3写1个字节.
4利润:)
f = open('newfile',"wb")
f.seek(1073741824-1)
f.write(b"\0")
f.close()
import os
os.stat("newfile").st_size
1073741824
UPD: 在我的系统(Linux + ReiserFS)上查找和截断这两个都将创建稀疏文件.它们具有所需的大小,但实际上不占用存储设备上的空间.因此,这不是快速分配空间的正确解决方案.我刚刚创建了100Gib文件,该文件只有25Gib可用,但结果仍然有25Gib可用.
UPD: Seek and truncate both create sparse files on my system (Linux + ReiserFS). They have size as needed but don't consume space on storage device in fact. So this can not be proper solution for fast space allocation. I have just created 100Gib file having only 25Gib free and still have 25Gib free in result.
次要更新:
为了与Py3兼容,在f.write("\0")
中添加了b
前缀.
Minor Update:
Added b
prefix to f.write("\0")
for Py3 compatibility.
这篇关于在python中创建特定大小的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!