Read b-string from file
Question:
I have a txt file that contains lines like b'111rn222rn333'
.
When I read the file with
with open('raw2.txt', 'r') as f:
nums = f.read().splitlines()
then the b-rows are turned into regular strings.
"b'111\r\n222\r\n333'"
If I read as ‘rb’, these lines become binary
b"b'111\r\n222\r\n333'"
How do I read the file correctly so that they look like:
b'111rn222rn333'
?
Thanks
Answers:
Use ast.literal_eval()
to parse the literal syntax.
import ast
with open('raw2.txt', 'r') as f:
nums = list(map(ast.literal_eval, f.read().splitlines()))
I have a txt file that contains lines like b'111rn222rn333'
.
When I read the file with
with open('raw2.txt', 'r') as f:
nums = f.read().splitlines()
then the b-rows are turned into regular strings.
"b'111\r\n222\r\n333'"
If I read as ‘rb’, these lines become binary
b"b'111\r\n222\r\n333'"
How do I read the file correctly so that they look like:
b'111rn222rn333'
?
Thanks
Use ast.literal_eval()
to parse the literal syntax.
import ast
with open('raw2.txt', 'r') as f:
nums = list(map(ast.literal_eval, f.read().splitlines()))