Home > OS >  Read lines from a text file containing dictionaries into elements of list
Read lines from a text file containing dictionaries into elements of list

Time:08-19

I have a text file that looks like this

{'tableName': 'customer', 'type': 'VIEW'}
{'tableName': 'supplier', 'type': 'TABLE'}
{'tableName': 'owner', 'type': 'VIEW'}

I want to read it into a python program that stores it into a list of dictonaries like this

expectedOutput=[{'tableName': 'customer', 'type': 'VIEW'},{'tableName': 'supplier', 'type': 'TABLE'},{'tableName': 'owner', 'type': 'VIEW'}]

But the output I get is a list of strings

       output = ["{'tableName': 'customer', 'type': 'VIEW'}",
      "{'tableName': 'supplier', 'type': 'TABLE'}",
      "{'tableName': 'owner', 'type': 'VIEW'}"] 

The code I run is

my_file3 = open("textFiles/python.txt", "r")
data3 = my_file3.read()
output = data3.split("\n") 

Can someone show me how do I store the entries inside the list as dicts and not strings. Thank you

CodePudding user response:

You can use eval but it can be dangerous (only do this if you trust the file):

my_file3 = open("textFiles/python.txt") # specifying 'r' is unnecessary
data3 = my_file3.read()
output = [eval(line) for line in data3.splitlines()] # use splitlines() rather than split('\n')

If the file contains something like __import__('shutil').rmtree('/') it could be very dangerous. Read the documentation for eval here


If you don't fully trust the file, use ast.literal_eval:

import ast
my_file3 = open("textFiles/python.txt")
data3 = my_file3.read()
output = [ast.literal_eval(line) for line in data3.splitlines()]

This removes the risk - if the file contains something like an import, it will raise a ValueError: malformed node or string. Read the documentation for ast.literal_eval here


Output:

[{'tableName': 'customer', 'type': 'VIEW'},
 {'tableName': 'supplier', 'type': 'TABLE'},
 {'tableName': 'owner', 'type': 'VIEW'}]

CodePudding user response:

You can use the json module

import json
my_file3 = open("textFiles/python.txt", "r")
data3 = my_file3.read()
output = json.loads(str(data3.splitlines()))
print(output)

As Thonnu warned, eval is quite dangerous

  • Related