I am trying to write a program that will encrypt a file by using the .read() function on the file content, which returns 98\xf1\xc6}xb1\*.... I am trying to encrypt the file by looping through each character an incrementing its decimal number by 1 (numbers range from 0 -> 255). and then adding each incremented number to a new list.
new list looks something like this:
['«', 'û', '$', '\x00', 'Ú']...
How do i convert this new list into a format which can be written in binary mode?
class Encrypting():
def __init__(self):
self.file = "files/test_img.jpg"
def open_file(self):
f = open(self.file, "rb")
self.content = f.read()
print(self.content)
f.close()
def convert_file_data(self):
self.new_values = []
for i in self.content:
new_val = i + 1
if i == 255:
new_val = 0
new_val = chr(new_val)
self.new_values.append(new_val)
def rewrite(self):
f = open("files/conv1.jpg", "wb")
f.write(self.new_values)
f.close()
def main():
encrypt = Encrypting()
encrypt.open_file()
encrypt.convert_file_data()
encrypt.rewrite()
if __name__ == "__main__":
main()
You could change:
to:
combining the
listofstrinto a singlestr, then encoding it tolatin-1(which is the 1-1 mapping of the first 256 Unicode ordinals to bytes of the same values).But the real solution is to change:
to:
This part:
could be simplified to:
as well, which could then simplify the whole function to:
or even shorter, a simple genexpr fed to the
bytes/bytearrayconstructor:Any of the
bytesorbytearraybased solutions are superior to storing alistofstrin that:strs are likely cached, but the pointers to them stored in thelistrequire 4-8 bytes a piece, vs. just one byte a piece for the rawbytes)joinandencodethe data, it's already in the correct form natively)