Warm tip: This article is reproduced from stackoverflow.com, please click
file python python-3.7.4

Why File.write() can't handling the tuple

发布于 2020-04-08 23:46:06

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 Write Byte mode When Running Append Byte mode When Running Append Byte mode Required Result Required Result

I Search everywhere and still, I can't find the answer where the bug is happening.

Questioner
Keerthi Naathan H
Viewed
91
Tommaso Fontana 2020-02-03 04:47

Simplification of the code

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)

Edit: Simplest way

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))