Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read list formatted data from file in python

Tags:

python

list

I know this must be a simple question for you all. I have textfile with test cases written in below list format,                                         

[["arg1", "arg2", "arg3"], "Fail"]

[["arg1", "arg2", "arg4"], "Pass"]

. . .

And I want to read this file in a list such a that, I can print list1[1] => "Fail".

thanks for your help.

like image 695
Pravin Junnarkar Avatar asked Dec 14 '25 04:12

Pravin Junnarkar


2 Answers

You can use ast.literal_eval() to safe convert the string line to a python expression

Example:

import ast

with open('list.txt') as f:
    lines = f.readlines()

data = [ast.literal_eval(line) for line in lines]

for item in data:
    print(item[1])
like image 72
Sergey Tolokonnikov Avatar answered Dec 16 '25 20:12

Sergey Tolokonnikov


Assumptions

  • You have a .txt file.
  • Format of a line is [["arg1", "arg2", "arg3",...etc.], "Fail/Pass"]

Approach is to use regex to find all text between double quotes and append to the list. The last one is taken as "Fail/Pass" and rest of them are args.

import re

result = []

with open('text.txt','r') as f:
    for line in f:
        match = re.findall("\"(.*?)\"",line.strip())
        result.append([match[:-1],match[-1]])

print(result)
print(result[0][0])
print(result[0][1])

Sample Input .txt file

[["arg1", "arg2", "arg3","arg4"], "Fail"]
[["arg1", "arg2", "arg4"], "Pass"]

Output

[[['arg1', 'arg2', 'arg3', 'arg4'], 'Fail'], [['arg1', 'arg2', 'arg4'], 'Pass']]
['arg1', 'arg2', 'arg3', 'arg4']
Fail
like image 24
Ajay Dabas Avatar answered Dec 16 '25 21:12

Ajay Dabas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!