I have an text file named “ex23_RawBytes_ConvertedToBytes.txt”
These are just text with class ‘_io.TextIOWrapper’ when I checked type in python
Any way I can convert them into bytes?
The reason I am doing this is that I have all the raw bytes in text but their type is not actually ‘bytes’ which is needed by me to convert them to cooked strings.
Just to be very clear: _io.TextIOWrapper is the return type from open(filename). It has nothing to do directly with the type of the data in the file, but the mode in which it is being read, and represents the object from which you will read the data.
In this case open(filename) is the same as open(filename, 'rt') which opens the file for reading “text”, and readline() will then give a str; changing to open(filename, 'rb') opens in binary mode, which gives a type of _io.BufferedReader and readline will give bytes.
The issue is the recursive call to main (as @barry-scott pointed out).
Try this:
def check(path, encoding="utf-8", errors="strict"):
with open(path, "rb") as f:
for lineno, line in enumerate(f):
try:
cooked = line.decode(encoding, errors)
except Exception as exc:
# print some error message
continue
try:
raw = cooked.encode(encoding, errors)
except Exception as exc:
# print some error message
continue
# you could add here:
# assert raw == line
# for comparison it's nicer to print one under the other:
print(f"{lineno:04}: {raw}")
print(f"{lineno:04}: {repr(cooked)}")