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.
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])
Assumptions
.txt file.[["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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With