I know the following command can generate 1GB file in Python. But if I want the txt file content is words "A" and the size is 1GB , how to code it?
Thank you!
f = open('newfile.txt',"wb")
f.seek(1073741824-1)
f.write(b"\0")
f.close()
Expect result:
many AAAAAAAA in the txt file and the size is 1GB.
CodePudding user response:
you have to do it one character at the time, or whatever you want to fill the file with at the time
def create_file(path:str, size:int=30, fill:str=""):
with open(path,"wb") as file:
if not fill:
file.seek(2**size -1)
file.write(b"\0")
return
fill = fill.encode()
for i in range((2**size)//len(fill)):
file.write(fill)
here because we are working on bytes, in the case we want to fill it with something we need to change it from str to bytes with encode and size is the necessary power of two to get the desire size, for 1GB that is 30
>>> create_file("test file 1GB.txt",fill='A')
>>> with open("test file 1GB.txt") as file:
... file.read(10)
...
...
'AAAAAAAAAA'
>>> import os
>>> os.stat("test file 1GB.txt").st_size
1073741824
>>> create_file("test file.txt",5,'ABC')
>>> with open("test file.txt") as file:
... file.read(10)
...
...
'ABCABCABCA'
>>> os.stat("test file.txt").st_size
30
>>>