File txt for list in python

1

I have several files with shape values:

0.4350    0.8798    0.0099         1
0.4375    0.8674    0.0090         1
0.4400    0.8682    0.0082         1

How do I load these files into Python in the way

   [[0.4350, 0.8798, 0.0099, 1],
    [0.4375, 0.8674, 0.0090, 1],
    [0.4400, 0.8682, 0.0082, 1]]

To be able to graph them from them?

    
asked by anonymous 30.04.2017 / 16:35

2 answers

3

Considering that the file only has data in the format mentioned, we can turn it into a list of lists list comprehension .

Using best practices to open and manipulate files, the code to process this data looks like this:

with open('dados.txt', 'r') as f:
    results = [[float(entry) for entry in line.split()] for line in f.readlines()]
    print(results)

Result

[[0.435, 0.8798, 0.0099, 1.0], [0.4375, 0.8674, 0.009, 1.0], [0.44, 0.8682, 0.0082, 1.0]]

How It Works

First iterate in all rows of the file in for outermost. For each line of the file, the split (of the string) is executed to separate the values in a new list used by the internal for . Then the function float does the string cast to float.

    
30.04.2017 / 22:58
1

Let's consider the file named values.txt with the following content:

0.4350  
0.8798  
0.0099 1 0.4375 0.8674 
0.0090 1 0.4400 0.8682  
0.0082 1

So I "developed" the code below, which is actually a part this answer .

Code

# Load File
lf = list(open('valores.txt','r'))

# Remove /n
lf = [s.rstrip() for s in lf]

# Convert into a list of list
lfl = [_str.split(' ') for _str in lf]

# Apresenta os resultados 
print (lfl)

Outcome:

[['0.4350'], ['0.8798'], ['0.0099', '1', '0.4375', '0.8674'], 
 ['0.0090', '1', '0.4400', '0.8682'], ['0.0082', '1']]

DEMO IN JUPYTER NOTEBOOK.

    
30.04.2017 / 17:09