Home > other >  Conversion to list of list from a file in python
Conversion to list of list from a file in python

Time:12-07

I am trying to execute a C file from a python code by running the C executable. Below is my code:

import subprocess
import sys

dataset = sys.argv[1]
def func():
    subprocess.run(['/home/dev/exec_file', dataset, 'outfile'])
    f_result = []
    f = open('outfile', "r")
    content = f. read()
    f_result.append(content)
    print(f_result)
    #print(content.rstrip('\n'))
    return f_result

Here if I simply write print(content.rstrip('\n')) then it gives output like:

*,*,1,*,0
*,*,2,2,1
*,*,*,3,1
*,*,*,4,2
*,*,3,*,2

Now I want to return a list of list. I mean it will look like:

[['*', '*', '1', '*', '0'], ['*', '*', '2', '2', '1'], ['*', '*', '*', '3', '1'], ['*', '*', '*', '4', '2'], ['*', '*', '3', '*', '2']]

In my above approach print(f_result) is giving output like: ['*,*,1,*,0\n*,*,2,2,1\n*,*,*,3,1\n*,*,*,4,2\n*,*,3,*,2\n']

How can I do it and return a list of list from this? Please help.

CodePudding user response:

Use a list comprehension and str.split:

content = '*,*,1,*,0\n*,*,2,2,1\n*,*,*,3,1\n*,*,*,4,2\n*,*,3,*,2\n'

[l.split(',') for l in content.rstrip('\n').split('\n')]

output:

[['*', '*', '1', '*', '0'],
 ['*', '*', '2', '2', '1'],
 ['*', '*', '*', '3', '1'],
 ['*', '*', '*', '4', '2'],
 ['*', '*', '3', '*', '2']]
  • Related