0

I have a .txt file with variable information and I need to read it to transform them into objects, the file is written as lists and dictionaries, is there an easy way to read them in this format?

this is an example of what is written in the txt:

[
 {
  "arg1":value1,
  "arg2":value2
 },
 {
  "arg1":value3,
  "arg2":value4
 },
]
2
  • 1
    What are the values? Are they really as shown, without quotes around them? Commented Aug 23, 2015 at 23:35
  • What you've shown is not valid JSON. Where is this data coming from, and do you have control over the source? Commented Aug 23, 2015 at 23:38

3 Answers 3

1

This is valid JSON; use the json module.

import json

with open('file.txt', 'r') as infile:
    data = json.load(infile)
Sign up to request clarification or add additional context in comments.

3 Comments

Aah, it's not quite valid JSON because of that last comma and non-quoted non-number values. I'll edit or delete based on clarifications.
Answer first, then ask questions?
@martineau, not intentionally. I answered, then realized a problem and asked for clarification. :)
1

You could interpret your input data as yaml format:

import yaml 

with open('data.txt') as file:
    data = yaml.safe_load(file)

Result

[{'arg1': 'value1', 'arg2': 'value2'}, {'arg1': 'value3', 'arg2': 'value4'}]

Comments

0

If it's only lists and dictionaries you can use ast.literal_eval. For your example:

>>> import ast
>>> content = open('input.txt').read()
>>> lst = ast.literal_eval(content)
>>> lst
[{'arg1': 'value1', 'arg2': 'value2'}, {'arg1': 'value3', 'arg2': 'value4'}]

Note that I also quoted the values, otherwise there would be an error when evaluating the string. But if the values are numbers it will work normally.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.