I am trying to read a file which contains ASCII values in the format: 072069076076079.
I can copy every three characters manually and pass it to the chr() function manually, but it is a big file and it can take a long time.
I want to read the file completely and separate every three characters and pass it to the chr() function.
d = "072069076076079049050051"
for i in range(len(d)//3):
print('{0}'.format(chr(int(d[i*3:i*3+3]))), end='')
This works, it prints "HELLO123".
with open('sample_ascii_file.txt', 'r') as f:
data = f.read()
print(data)
This prints the ASCII values, 072069076076079049050051.
with open('sample_ascii_file.txt', 'r') as f:
data = f.read()
print(chr(data))
It gives error (I want to read three characters at a time and then pass it to the chr() function).
In the first code container you gave an answer to your own question I think. I just don't get why you wouldn't apply it in the third container.
from textwrap import wrap # built-in module
with open('sample_ascii_file.txt', 'r') as f:
# "Split string every nth character" - https://stackoverflow.com/a/48860937/4620679
text = ''.join( chr(int(s)) for s in wrap(f.read(), 3) )
print(text)
# alternative (also posted in that stackoverflow topic)
# text = ''.join( [chr(int(data[i:i+3])) for i in range(0, len(data), 3)] )