1

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.

Mohan Singh
  • 1,142
  • 3
  • 15
  • 30
Pravin Junnarkar
  • 800
  • 1
  • 5
  • 13

7 Answers7

3

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])
2

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
Ajay Dabas
  • 1,404
  • 1
  • 5
  • 15
2

Just use eval , its internal python function and you dont need libraries.

Example:

lists = []
line1 = '[["arg1", "arg2", "arg3"], "Fail"]'
line2 = '[["arg1", "arg2", "arg4"], "Pass"]'
# Evaluate Lines
exLine1 = eval(line1)
exLine2 = eval(line2)
# Append Lines to lists
lists.append(exLine1)
lists.append(exLine2)
# Testing Example of your use case
print(str(exLine1[1] == "Fail"))

Just Convert this example to for loop you are using and it will be fast and simple

  • 1
    You must never use `eval()` in python. Read [Why is using 'eval' a bad practice?](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice) – Ajay Dabas Jan 15 '20 at 03:38
1

I would do like this.

sample myfile.txt:

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

Main python file.

file1 = open('myfile.txt', 'r') 
count = 0

while True: 
    count += 1

    # Get next line from file 
    list = file1.readline()
    if not list: 
        break
    #convert string to list
    res = list.strip('][').split(', ') 
    print(res[1])

After reading the file line by line, Convert the string of list into list by using split.

Deepak Raj
  • 316
  • 1
  • 10
  • Hello Deepak, thanks for your try. But you are reading all values in one list whereas I need list format as is in text file. – Pravin Junnarkar Jan 14 '20 at 16:09
  • Please refer this link for converting string representation of list to list https://www.geeksforgeeks.org/python-convert-a-string-representation-of-list-into-list/ – Deepak Raj Jan 15 '20 at 14:47
1

You can hack together some pretty simple string manipulation code, as everyone is providing here. I've done it simply like this:

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

for line in text.strip().splitlines():
    line = line.replace('[', '')
    line = line.replace(']', '')
    print line.split(',')[-1].strip()

It's not pretty but you can do it plenty of better ways if you're looking to do this is production.

ev350
  • 429
  • 3
  • 16
1

you can try something like below:

with open("test.txt", "r") as test_file:
content = test_file.readlines()

print(content)
print(type(content))

for data in content:
    print(ast.literal_eval(data)[1])

print("*" * 30)
for i in range(1, len(content)+1):
    print(i)

output:

index:  0

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

index: 1

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

1
2
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Nasreen Ustad
  • 1,564
  • 1
  • 19
  • 24
0

What about this code example from link:

# load additional module
import pickle

with open('listfile.data', 'rb') as filehandle:
    # read the data as binary data stream
    placesList = pickle.load(filehandle)
Mohammed Deifallah
  • 1,290
  • 1
  • 10
  • 25