Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Read b-string from file

I have a txt file that contains lines like b'111\r\n222\r\n333'.

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"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'111\r\n222\r\n333'

?

Thanks

>Solution :

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()))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading