0

I'm trying to read a txt file containing multiple dictionaries. The file has the following format:

/* 1 */
{
    key1: val1,
    key2: val2
}

/* 2 */
{
    key1: val1,
    key2: val2
}

/* 3 */
{
}...

I'm trying to read it as a list of dictionaries. Is there any way to remove that /* x */ thing and do the needful? I tried the following piece of code but it doesn't seem to work:

import ast
  
with open('doc.txt') as f:
    data = f.read()
d = ast.literal_eval(data)
SrGrace
  • 326
  • 5
  • 16

1 Answers1

0

To remove /* x */ You can use regular expression

import ast
import re
  
with open('doc.txt') as f:
    data = re.sub("/\*.*\*/", "", f.read())

d = ast.literal_eval(data)

you can find more in official documentation: re

Raj
  • 80
  • 1
  • 8
  • It won't be able to read as the file contains byte-like objects '/* x */' – SrGrace May 10 '21 at 13:24
  • hope this helps you [a bytes-like object is required, not 'str' when writing to a file](https://stackoverflow.com/questions/33054527/typeerror-a-bytes-like-object-is-required-not-str-when-writing-to-a-file-in) @SrGrace – Raj May 10 '21 at 13:30