create file of particular size in python

前端 未结 2 963
余生分开走
余生分开走 2020-12-04 23:52

I want to create a file of particular size (say, 1GiB). The content is not important since I will fill stuff into it.

What I am doing is:

f = open(\"         


        
2条回答
  •  爱一瞬间的悲伤
    2020-12-05 00:31

    The question has been answered before. Not sure whether the solution is cross platform, but it works in Windows (NTFS file system) flawlessly.

    with open("file.to.create", "wb") as out:
        out.truncate(1024 * 1024 * 1024)
    

    This answer uses seek and write:

    with open("file.to.create", "wb") as out:
        out.seek((1024 * 1024 * 1024) - 1)
        out.write('\0')
    

提交回复
热议问题