-1

I want to read a file that has hex. For example the file contains this "\x70\x79\x74\x68\x6f\x6e\x70\x79\x74\x68\x6f\x6e\x70\x79\x74\x68\x6f\x6e".

I tried to read the file and print it but when I print it I see the same hex code and not the plaintext English. But when I manually copy the hex code into the print() function of Python, it shows the plaintext English. However, the print() function in the below function only shows the hex code and not English.

with open('sample_hex_file_2.txt', 'r') as f:
    data = f.read()
    print(data)

I want to read the file that contains the hex code and convert it into English and print it on screen.

Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
Jon Snow
  • 13
  • 3
  • If I do this in perl, I get "pythonpythonpython": `print "\x70\x79\x74\x68\x6f\x6e\x70\x79\x74\x68\x6f\x6e\x70\x79\x74\x68\x6f\x6e"`. SHouldn't be that hard in any other language. Of course you could do that yourself, too. So what's the question? – U. Windl May 14 '19 at 08:13
  • 1
    Possible duplicate of [Convert from ASCII string encoded in Hex to plain ASCII?](https://stackoverflow.com/questions/9641440/convert-from-ascii-string-encoded-in-hex-to-plain-ascii) – user2653663 May 14 '19 at 08:13

1 Answers1

0

Please tell me you can remove the quotes on the input file? Once we are through that hurdle, you can use this.

def main():
    with open('sample_hex_file_2.txt', 'r') as f:
        data = f.read()
        text=""
        for item in data.split('\\x'):
            text += (bytearray.fromhex(item).decode())
        print(text)
if __name__== "__main__":
    main()

Leads to pythonpythonpython

iAmTryingOK
  • 216
  • 1
  • 10