简体   繁体   中英

Importing data from a file as a float in python

I have a file, variables.txt , when I input a float, say 7.75 , it inputs it into the file as 7.75 . When I get the information back from the file, I get ['7.75'] . I'm assuming this is a list. How would I be able to change ['7.75'] back to a float, 7.75, so that it can be multiplied, divided, etc.

将列表中的第一个条目转换为float()值:

value = float(somelist[0])

This code will open a text file with a float on each line and give you a list of float s

with open('floats.txt', 'r') as f:
    floats = []
    for each in f:
        floats.append(float(each.strip()))

print(floats)

you can then access each float in the list by it's index:

float[0] #this will give you the first entry in the list

File:

7.75
1.23
4.56

Output:

[7.75, 1.23, 4.56]

In Python, how do I convert all of the items in a list to floats?

To reiterate, you want to loop through the list and convert all element to float values using the "float" function.

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