MCPcopy
hub / github.com/TheAlgorithms/Python / write_file_binary

Function write_file_binary

data_compression/lempel_ziv.py:86–110  ·  view source on GitHub ↗

Writes given to_write string (should only consist of 0's and 1's) as bytes in the file

(file_path: str, to_write: str)

Source from the content-addressed store, hash-verified

84
85
86def write_file_binary(file_path: str, to_write: str) -> None:
87 """
88 Writes given to_write string (should only consist of 0's and 1's) as bytes in the
89 file
90 """
91 byte_length = 8
92 try:
93 with open(file_path, "wb") as opened_file:
94 result_byte_array = [
95 to_write[i : i + byte_length]
96 for i in range(0, len(to_write), byte_length)
97 ]
98
99 if len(result_byte_array[-1]) % byte_length == 0:
100 result_byte_array.append("10000000")
101 else:
102 result_byte_array[-1] += "1" + "0" * (
103 byte_length - len(result_byte_array[-1]) - 1
104 )
105
106 for elem in result_byte_array:
107 opened_file.write(int(elem, 2).to_bytes(1, byteorder="big"))
108 except OSError:
109 print("File not accessible")
110 sys.exit()
111
112
113def compress(source_path: str, destination_path: str) -> None:

Callers 1

compressFunction · 0.70

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected