Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Read ASCII File
#1
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.
Reply
#2
so, what have you tried?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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).
Reply
#4
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)] )
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to read a file as binary or hex "string" so that I can do regex search? tatahuft 3 1,158 Dec-19-2024, 11:57 AM
Last Post: snippsat
  Read TXT file in Pandas and save to Parquet zinho 2 1,282 Sep-15-2024, 06:14 PM
Last Post: zinho
  [solved] how to delete the 10 first lines of an ascii file paul18fr 7 1,836 Aug-07-2024, 08:18 PM
Last Post: Gribouillis
  Pycharm can't read file Genericgamemaker 5 1,608 Jul-24-2024, 08:10 PM
Last Post: deanhystad
  Python is unable to read file Genericgamemaker 13 3,854 Jul-19-2024, 06:42 PM
Last Post: snippsat
  Reading an ASCII text file and parsing data... oradba4u 2 1,461 Jun-08-2024, 12:41 AM
Last Post: oradba4u
  Connecting to Remote Server to read contents of a file ChaitanyaSharma 1 3,352 May-03-2024, 07:23 AM
Last Post: Pedroski55
  Recommended way to read/create PDF file? Winfried 3 4,877 Nov-26-2023, 07:51 AM
Last Post: Pedroski55
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 3,901 Nov-09-2023, 10:56 AM
Last Post: mg24
  read file txt on my pc to telegram bot api Tupa 0 2,649 Jul-06-2023, 01:52 AM
Last Post: Tupa

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020