简体   繁体   中英

How to get floats from text file in python?

Hi I am new to python and I have a textfile .txt with the following structure:

Text1     31332.22342
Text2     293023.32323
Text3     32332.32323

What is the easiest way to get those numbers into an array? Cheers!

You can read the file and split it into aa list, then iterate through the list and try to convert to a float, if its successful then add it to the floats list. like the following:

    with open('file.txt', 'r') as f:
        data = f.read().split()
        floats = []
        for elem in data:
            try:
                floats.append(float(elem))
            except ValueError:
                pass
        print floats

output:

[31332.22342, 293023.32323, 32332.32323]

You also can use numpy genfromtxt function. something like this:

text_file.txt

Text1     31332.22342
Text2     293023.32323
Text3     32332.32323

python shell

>>> import numpy as np
>>> numbers = np.genfromtxt('text_file.txt', usecols=1 )

output

[  31332.22342  293023.32323   32332.32323]

To get propert validation of your data type try this:

import numpy as np
data = np.genfromtxt("test.txt", usecols=1, dtype=float)

Output:

[  31332.22342  293023.32323   32332.32323]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM