Load data from Python files into a list

Asked 2 years ago, Updated 2 years ago, 166 views

I'd like to bring the file (data.txt) that has the following data to the list and process it.

[skkim@master test]$ cat data.txt 
0.367763
0.335844
0.333843
0.333408
0.0741867
0.0189132
0.00119196
0.00676449
0.00847439
0.0105101
0.119838
0.130812
0.136221
0.468357
0.468717

It's a file like this.

In a Python Environment

data = open('./data.txt')
data.split()
print(data)

I don't think this is how you do it. The following message appears.

    data.split()
AttributeError: 'file' object has no attribute 'split'

python list save load

2022-09-22 20:58

2 Answers

data = open('./data.txt')
[float(num) for num in data.read().split()]

Would you like to do it with

data.read().split() will read the data, and the part between the brackets [] is the process of converting the string array into a float array using list compression.


2022-09-22 20:58

Thank you.

I think the problem is that the number is read as string.

If you print it out...

['0.367763', '0.335844', '0.333843', '0.333408', '0.0741867', '0.0189132', '0.00119196', '0.00676449', '0.00847439', '0.0105101', '0.119838', '0.130812', '0.136221', '0.468357', '0.468717']

It comes out like this, but I have to input the number as data and process it... I ask for your help.

Thank you.


2022-09-22 20:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.