0

I have a text file with a list of strings on every line, something like:

['abc', 'def', 'ghi']
['jkl', 'mn']
['opqr', "s'tu'v", 'w', 'xyz']

I am trying to read each line of the file and append each list to a bigger list. Currently I am trying something like this:

with open("file.txt") as file_in:
    lines = []
    for line in file_in:
        lines.append(line)

lines = [x.strip() for x in lines] 

However, each list is being added in as a string, rather than a list, and thus the output trying print(lines) would be something like:

["['abc,  'def', 'ghi']", "['jkl', 'mn']", ...

I'm not sure if I should be converting each line into a list and then appending it into a larger list, or if there is a better method to doing this.

Bernie Zhu
  • 33
  • 4
  • Where is the list generated? I would dump each line to the list using `json.dumps` such that you can safely read it again with `json.loads` – flakes Jun 17 '21 at 14:45
  • Change `lines.append(line)` to `lines.append(ast.literal_eval(line.strip('\n')))`. Don't forget to `import ast` – ThePyGuy Jun 17 '21 at 14:47

0 Answers0