Modifying binary files using Python memory views
Python Memory Views Data Type: Exercise-5 with Solution
Write a Python program that reads a binary file into a memory view and saves a modified copy.
Sample Solution:
Code:
def modify_file_data(data):
# Example modification: adding 10 to each byte
for i in range(len(data)):
data[i] = (data[i] + 10) % 256
def main():
input_file_path = "fontawesome_webfont.bin"
output_file_path = "output.bin"
# Read binary data from input file into a bytearray
with open(input_file_path, "rb") as input_file:
input_data = input_file.read()
input_bytearray = bytearray(input_data)
# Create a memory view from the bytearray
memory_view = memoryview(input_bytearray)
# Modify the data using the memory view
modify_file_data(memory_view)
# Save the modified data to an output file
with open(output_file_path, "wb") as output_file:
output_file.write(memory_view)
print("File modification complete.")
if __name__ == "__main__":
main()
Output:
File modification complete.
In the exercise above, the binary data is read from the input file into a 'bytearray', which is writable. Then, a memory view is created from this writable 'bytearray'. The "modify_file_data()" function modifies the bytearray data through the memory view. Finally, the modified data is written to an output file.
Flowchart:
Previous: Calculating average with NumPy memory view in Python.
Next: Concatenating memory views in Python: Function and example.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/extended-data-types/python-extended-data-types-index-memory-views-exercise-5.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics