txt file for python list

Asked

Viewed 2,406 times

1

I have several files with values of the form:

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 Python files in the form

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

to make a chart from them?

2 answers

3

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

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

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

Upshot

[[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 we iterate on all lines of the file on for external. For each line of the file, the split (string) to separate the values into a new list used by for internal. Then the function float makes the string cast to float.

1

Let’s consider the file called txt values. 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 of that 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)

Upshot:

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

DEMO ON JUPYTER NOTEBOOK.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.