Reading a Text File and Converting String to Float

Reading a text file and converting string to float

Edit:

commented by martineau:
you can also use if y: to eliminate None or empty string.

Original Answer:

It fails due to you are using newline character as a separator, therefore the last element is empty string

you can add y.isdigit() to check whether y is numeric.

x = []
file_in = open('sample.csv', 'r')
for y in file_in.read().split('\n'):
if y.isdigit():
x.append(float(y))

OR

you can change read().split("\n") to readlines()

OR

remove the leading/trailing characters from y. it handles the lines with extra whitespaces

for y in file_in:
trimed_line = y.strip() # leading or trailing characters are removed

Reading strings and floats from a text file

I had the requirement to get the data line by line, assuming every three lines was a new student. My next requirement was that the third line would be a float but getline() reads in as a string.

My solution was to just create a temporary variable to take the string and then convert it to a float on the fly.

#include <iomanip>
#include <ios>
#include <iostream>
#include <iterator>
#include <list>
#include <fstream>

struct Student {
std::string name;
std::string course;
std::string grade;
float mark;
};

int main() {

Student students [6];
std::string filename = "data.txt";
std::ifstream file(filename);

int i = 0;

while(getline(file, students[i].name))
{
getline(file, students[i].course);

string mark; // <-- to hold the string
getline(file, mark);
students[i].mark = std::stof(mark);

if (students[i].mark > 89.5) {
students[i].grade = "HD";
} else {
students[i].grade = "PASS";
}

++i;
}

return 0;
}
``

How to convert a string into a float when reading from a text file

At the end of the second line, you have a comma, so you have an empty string in the list. float('') raise an exception, hence your error:

for line in input_file:
for numstr in line.split(","):
if numstr:
try:
numFl = float(numstr)
print(numFl)
except ValueError as e:
print(e)

As said in comments, avoid to catch Exception and try to have the minimum lines of code in a try/except to avoid silent errors.

Reading from a file and converting to a float in Python

Here is the final solution:

You can minimize the code lines:

file = open("fileName.txt", "r+")
value = file.readlines()
for i in value:
file.seek(0)
file.write(str(float(i)+value you want to add))

How to read text file as list of floats?

Your data is valid JSON, so just use the corresponding module that will take care of all the parsing for you:

import json

with open("data.txt") as f:
data = json.load(f)

print(data)

Output:

[1130.1271455966723, 1363.3947962724474, 784.433380329118, 847.2140341725295, 803.0276763894814]

Could not convert string to float - Reading from the fil

Use a try/except, use with to open your files and just iterate over the file object f. You don't need a while loop to read a file. The iteration will stop when you reach the end of the file:

with open('coffee.txt', 'r') as f: # closes automatically
for qty in f:
try:
qty = float(qty) # try to cast to float
except ValueError:
pass
print(qty) # will either be a float or Coffee 1 etc..

If the floats are every second line we can skip lines using next because a file object returns it's own iterator:

with open('coffee.txt', 'r') as f:
next(f) # skip very first line
for qty in f:
qty = float(qty)
next(f,"") # skips every other line
print(qty)

Output:

18.0
25.0

If there file s not very large we can use map to map to floats and get every second element slicing readlines:

with open('coffee.txt', 'r') as f:
floats = map(float,f.readlines()[1::2]) # start at second element and get every second element after
print(list(floats))
[18.0, 25.0]

You don't need to strip to cast to float:

In [5]: float(" 33 ")
Out[5]: 33.0

In [6]: float(" 33 \n")
Out[6]: 33.0


Related Topics



Leave a reply



Submit