I am developing a Customized File Shredder.
I want to write tuple values bytes inside the files.
for example: If i pass 3 variable (0,100,1) # 'b'00, 'b'd, 'b'01 and the File Size is 200 Bytes. for 200/3 = 66 times it will write all the tuple data. and in last round 200%3 = 2 so it will write the first 2 tuple data. when I tried to implement it, it goes wrong.
When i used write byte mode:
def multiple_writer(self, val:tuple):
with open(self.file_path, 'wb+') as file:
file_current = 0
main_mode = True
while file_current < self.file_size:
if main_mode:
for values in val:
if file_current <= self.file_size:
file.write(values)
file_current += 1
else:
main_mode = False
break
else:
break
When i used append byte mode:
def multiple_writer(self, val:tuple):
with open(self.file_path, 'ab+') as file:
file_current = 0
main_mode = True
file.seek(0)
while file_current < self.file_size:
if main_mode:
for values in val:
if file_current <= self.file_size:
file.write(values)
file_current += 1
else:
main_mode = False
break
else:
break
My Result is :
When Running Write Byte mode
When Running Append Byte mode
Required Result
I Search everywhere and still, I can't find the answer where the bug is happening.
If we define a helper function which returns cyclically the data from the tuple:
def cyclic_iter(values):
while True:
for v in values:
yield v
then the code could simply become:
def multiple_writer(self, val:tuple):
with open(self.file_path, 'wb+') as file:
generator = cyclic_iter(val)
for _ in range(self.file_size):
file.write(next(generator))
or one could exploit the zip
function:
def multiple_writer(self, val:tuple):
with open(self.file_path, 'wb+') as file:
for _, value in zip(range(self.file_size), cyclic_iter(val)):
file.write(value)
Since you mentioned that you just started with python I'll add the simplest way I know.
def multiple_writer(self, val:tuple):
with open(self.file_path, 'wb+') as file:
for i in range(self.file_size):
file.write(val[i % len(val))
Thanks for the help it works, because i am new to this community and python language and i am working on my first project. so i tried to find the answer but i can't found.
No problem! Python it's really simple but it takes time to learn all its nuances. So Good luck!
file.seek(0)
andfile.seek(0, 0)
are equivalent, as explained in the documentation you cited.ops, you are right