1

Python shows a literal string value, and uses escape codes in the console:

>>> x = '\x74\x65\x73\x74'
>>> x
'test'
>>> print(x)
test

How can I do the same when reading from a file?

$ cat test.txt 
\x74\x65\x73\x74

$ cat test.py 
with open('test.txt') as fd:
    for line in fd:
        line = line.strip()
        print(line)

$ python3 test.py
\x74\x65\x73\x74
2

2 Answers 2

1

using string encode and decode function

refer this for python standard encodings

for python 2

line = "\\x74\\x65\\x73\\x74"
line = line.decode('string_escape')
# test

for python3

line = "\\x74\\x65\\x73\\x74"
line = line.encode('utf-8').decode('unicode_escape')
# test
Sign up to request clarification or add additional context in comments.

Comments

0

Read the file in binary mode to preserve the hex representation into a bytes-like sequence of escaped hex characters. Then use bytes.decode to convert from a bytes-like object to a regular str. You can use the unicode_escape Python-specific encoding as the encoding type.

$ cat test.txt
\x74\x65\x73\x74

$ cat test.py
with open('test.txt', "rb") as fd:
    for line in fd:
        print(line)
        print(line.decode("unicode_escape"))

$ python3 test.py
b'\\x74\\x65\\x73\\x74\n'
test

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.