Home > OS >  How do I read in a txt file as a dictionary in Python?
How do I read in a txt file as a dictionary in Python?

Time:10-21

I have a txt file that is of the following format (dictionary format):

{'EX1':'No Information Stored',
'EX2':'Foundation',
'EX3':'Foundation',
'EX4':'No Information Stored'}

Does anyone know how I would go about reading this into python to be able to use it like the dictionary that it is?

CodePudding user response:

import json

with open('file.txt', 'r') as w:
   data = w.read()
   data_as_dict = json.loads(data)

CodePudding user response:

Text file with this structure are JSON, so you can use the json module.

import json

def load_file(filename):
    with open(filename) as f:
        data = json.load(f)
        return data

This is a custom function that return the dictionary you want.

CodePudding user response:

Using the ast.literal_eval(). It can be used for conversion of other data types as well

    # importing the module
import ast
  
# reading the data from the file
with open('dictionary.txt') as f:
    data = f.read()
        
# reconstructing the data as a dictionary
d = ast.literal_eval(data)
  
print(d)

CodePudding user response:

There are two methods for this,

1. Method using json.load():

.load() use to get from directly form file

import json
  
with open('data.json') as f:
   json.load(f)

2. Method using json.loads():

.loads() use to get from string. So we need to read the file first to get string.

import json
  
with open('data.json') as f:
   json.loads(f.read())
  • Related