Creating a file with $SIZE
Robert Bossy
Robert.Bossy at jouy.inra.fr
Thu Mar 13 03:54:56 EDT 2008
cokofreedom at gmail.com wrote:
> On Mar 12, 2:44 pm, Robert Bossy <Robert.Bo... at jouy.inra.fr> wrote:
>
>> Matt Nordhoff wrote:
>>
>>> Robert Bossy wrote:
>>>
>>>> k.i.n.g. wrote:
>>>>
>>>>> I think I am not clear with my question, I am sorry. Here goes the
>>>>> exact requirement.
>>>>>
>>>>> We use dd command in Linux to create a file with of required size. In
>>>>> similar way, on windows I would like to use python to take the size of
>>>>> the file( 50MB, 1GB ) as input from user and create a uncompressed
>>>>> file of the size given by the user.
>>>>>
>>>>> ex: If user input is 50M, script should create 50Mb of blank or empty
>>>>> file
>>>>>
>>>> def make_blank_file(path, size):
>>>> f = open(path, 'w')
>>>> f.seek(size - 1)
>>>> f.write('\0')
>>>> f.close()
>>>>
>>>> I'm not sure the f.seek() trick will work on all platforms, so you can:
>>>>
>>>> def make_blank_file(path, size):
>>>> f = open(path, 'w')
>>>> f.write('\0' * size)
>>>> f.close()
>>>>
>>> I point out that a 1 GB string is probably not a good idea.
>>>
>>> def make_blank_file(path, size):
>>> chunksize = 10485760 # 10 MB
>>> chunk = '\0' * chunksize
>>> left = size
>>> fh = open(path, 'wb')
>>> while left > chunksize:
>>> fh.write(chunk)
>>> left -= chunksize
>>> if left > 0:
>>> fh.write('\0' * left)
>>> fh.close()
>>>
>> Indeed! Maybe the best choice for chunksize would be the file's buffer
>> size... I won't search the doc how to get the file's buffer size because
>> I'm too cool to use that function and prefer the seek() option since
>> it's lighning fast regardless the size of the file and it takes near to
>> zero memory.
>>
>> Cheers,
>> RB
>>
>
> But what platforms does it work on / not work on?
>
Posix. It's been ages since I touched Windows, so I don't know if XP and
Vista are posix or not.
Though, as Marco Mariani mentioned, this may create a fragmented file.
It may or may not be an hindrance depending on what you want to do with
it, but the circumstances in which this is a problem are quite rare.
RB
More information about the Python-list
mailing list