473,385 Members | 1,912 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

ValueError: invalid literal for float():

TMS
119 100+
I'm working on a linear regression program and when I try to convert the input file data to a float (it reads in as a string), I get this error. Perhaps someone can help me? I'm using Windows XP, and IDLE. (also the console screen).

Expand|Select|Wrap|Line Numbers
  1. #! /usr/bin/env python
  2. import sys
  3. import os
  4. from numpy import * 
  5. numLst = [] #an empty list
  6. if len(sys.argv) == 2:
  7.     infile = open(sys.argv[1], 'r')
  8. elif len(sys.argv) <2:
  9.     infile = raw_input("Name of file: ")
  10. elif len(sys.argv) > 2:
  11.     raise SyntaxError, "Too many arguments"
  12. data = open(infile, 'r')
  13. for x in data:
  14.     x = float(x) # HERE IS THE PROBLEM
  15.     numLst.append(x.strip('\n').split(" "))
  16.  
  17. a = array(numLst)
  18. print a
  19.  
Input file looks like this:

1.0 2.0
2.0 3.5
2.5 5.0
3.5 6.5

which are data points, x and y respectively.

Thanks!

TMS
Apr 10 '07 #1
11 40786
bvdet
2,851 Expert Mod 2GB
I'm working on a linear regression program and when I try to convert the input file data to a float (it reads in as a string), I get this error. Perhaps someone can help me? I'm using Windows XP, and IDLE. (also the console screen).

Expand|Select|Wrap|Line Numbers
  1. #! /usr/bin/env python
  2. import sys
  3. import os
  4. from numpy import * 
  5. numLst = [] #an empty list
  6. if len(sys.argv) == 2:
  7.     infile = open(sys.argv[1], 'r')
  8. elif len(sys.argv) <2:
  9.     infile = raw_input("Name of file: ")
  10. elif len(sys.argv) > 2:
  11.     raise SyntaxError, "Too many arguments"
  12. data = open(infile, 'r')
  13. for x in data:
  14.     x = float(x) # HERE IS THE PROBLEM
  15.     numLst.append(x.strip('\n').split(" "))
  16.  
  17. a = array(numLst)
  18. print a
  19.  
Input file looks like this:

1.0 2.0
2.0 3.5
2.5 5.0
3.5 6.5

which are data points, x and y respectively.

Thanks!

TMS
Each iteration reads a line from the file. The argument to float must be in the correct format. See below:
Expand|Select|Wrap|Line Numbers
  1. >>> x = '1.0 2.0'
  2. >>> float(x)
  3. Traceback (most recent call last):
  4.   File "<interactive input>", line 1, in ?
  5. ValueError: invalid literal for float(): 1.0 2.0
  6. >>> x,y = [float(i) for i in x.split()]
  7. >>> x
  8. 1.0
  9. >>> y
  10. 2.0
  11. >>> 
Separate the numbers and pass each one to float().
Apr 10 '07 #2
ilikepython
844 Expert 512MB
I'm working on a linear regression program and when I try to convert the input file data to a float (it reads in as a string), I get this error. Perhaps someone can help me? I'm using Windows XP, and IDLE. (also the console screen).

Expand|Select|Wrap|Line Numbers
  1. #! /usr/bin/env python
  2. import sys
  3. import os
  4. from numpy import * 
  5. numLst = [] #an empty list
  6. if len(sys.argv) == 2:
  7.     infile = open(sys.argv[1], 'r')
  8. elif len(sys.argv) <2:
  9.     infile = raw_input("Name of file: ")
  10. elif len(sys.argv) > 2:
  11.     raise SyntaxError, "Too many arguments"
  12. data = open(infile, 'r')
  13. for x in data:
  14.     x = float(x) # HERE IS THE PROBLEM
  15.     numLst.append(x.strip('\n').split(" "))
  16.  
  17. a = array(numLst)
  18. print a
  19.  
Input file looks like this:

1.0 2.0
2.0 3.5
2.5 5.0
3.5 6.5

which are data points, x and y respectively.

Thanks!

TMS
Not sure about your error message but if sys.argv == 2 then wouldn't you be opening the file twice? Probably nothing to do with the problem but just thought I'd mention it.

Also, you didn't read the file. Try:
Expand|Select|Wrap|Line Numbers
  1. data = infile.read()
  2.  
I think that might work.
Apr 10 '07 #3
TMS
119 100+
ok, I see now. But I'm not sure how to use that with my for loop. Or do I use it in the for loop? Shouldn't I convert the file data to float before I append it to my list?
Apr 10 '07 #4
TMS
119 100+
Not sure about your error message but if sys.argv == 2 then wouldn't you be opening the file twice?

Also, you didn't read the file. Try:
Expand|Select|Wrap|Line Numbers
  1. data = infile.read()
  2.  
I think that might work.
No.
2 = the second argument in the file. Note the 'len' before sys.argv

It reads the file fine. That isn't the problem. I'm trying to convert the data from strings to floats.
Apr 10 '07 #5
ilikepython
844 Expert 512MB
No.
2 = the second argument in the file. Note the 'len' before sys.argv

It reads the file fine. That isn't the problem. I'm trying to convert the data from strings to floats.
Oh sorry, but for the file opening I meant
Expand|Select|Wrap|Line Numbers
  1.  
  2. if len(sys.argv) == 2:
  3.     infile = open(sys.argv[1], 'r')
  4. elif len(sys.argv) <2:
  5.     infile = raw_input("Name of file: ")
  6. elif len(sys.argv) > 2:
  7.     raise SyntaxError, "Too many arguments"
  8. data = open(infile, 'r')
  9.  
You have two open calls. I'm sorry if I'm being stupid but it doesn't really matter so forget about it.
Apr 10 '07 #6
TMS
119 100+
you aren't being stupid.
My assignment requires that only one file is provided on the command line.

Do you have a better way of doing it?

In tests what I've done works fine. If I provide more than one file I get an error, which is what I want.

Perhaps I'm missing something here. The first arg is 0, second is 1, etc. If the first arg is the program name, the second is the file name I want opened. So, the length of the args should equal 2 or there are two many args, right?
Apr 10 '07 #7
bvdet
2,851 Expert Mod 2GB
ok, I see now. But I'm not sure how to use that with my for loop. Or do I use it in the for loop? Shouldn't I convert the file data to float before I append it to my list?
Expand|Select|Wrap|Line Numbers
  1. >>> numList = []
  2. >>> fList = open('data_file').readlines()
  3. >>> for x in fList:
  4. ...     numList.append([float(i) for i in x.strip().split()])
  5. ...     
  6. >>> numList
  7. [[1.0, 2.0], [2.0, 3.5], [2.5, 5.0], [3.5, 6.5]]
  8. >>> 
If you create a file object, don't forget to close it. Done like above, no file object is created.
Apr 10 '07 #8
ilikepython
844 Expert 512MB
you aren't being stupid.
My assignment requires that only one file is provided on the command line.

Do you have a better way of doing it?

In tests what I've done works fine. If I provide more than one file I get an error, which is what I want.

Perhaps I'm missing something here. The first arg is 0, second is 1, etc. If the first arg is the program name, the second is the file name I want opened. So, the length of the args should equal 2 or there are two many args, right?
Ok, sys.argv[1] is the file name. Right? If that's the case then I believe you should get an error message. I tried it:
Expand|Select|Wrap|Line Numbers
  1. >>> infile = open("C:\\testfile.txt", "r")
  2. >>> data = open(infile, "r")
  3.  
  4. Traceback (most recent call last):
  5.   File "<pyshell#5>", line 1, in <module>
  6.     data = open(infile, "r")
  7. TypeError: coercing to Unicode: need string or buffer, file found
  8. >>> 
  9.  
Did it work for you?
Please correct me if I am wrong?
Apr 11 '07 #9
ghostdog74
511 Expert 256MB
something you might want to take a look
Expand|Select|Wrap|Line Numbers
  1. ....
  2. if len(sys.argv) == 2:
  3.     data = open(sys.argv[1], 'r')
  4. elif len(sys.argv) <2:
  5.     infile = raw_input("Name of file: ")
  6.         data = open(infile, 'r')
  7. elif len(sys.argv) > 2:
  8.     raise SyntaxError, "Too many arguments"
  9. for x in data:
  10. ....
  11.  
sys.argv[0] is the program name, argv[1] is the first argument and so on.
Apr 11 '07 #10
bvdet
2,851 Expert Mod 2GB
ok, I see now. But I'm not sure how to use that with my for loop. Or do I use it in the for loop? Shouldn't I convert the file data to float before I append it to my list?
Here's a one-liner:
Expand|Select|Wrap|Line Numbers
  1. >>> [[float(x),float(y)] for x,y in [j.split() for j in open('data.txt').read().split('\n')]]
  2. [[1.0, 2.0], [2.0, 3.5], [2.5, 5.0], [3.5, 6.5]]
  3. >>>
Apr 11 '07 #11
TMS
119 100+
YEAH!!! thank you. Now I can get down to the complexities of linear regression, which is more busy work than anything. Thank you!

This is what it looks like right now, there are no error messages:

Expand|Select|Wrap|Line Numbers
  1. #! /usr/bin/env python
  2. import sys
  3. import os
  4. from numpy import * 
  5. numLst = [] #an empty list
  6. if len(sys.argv) == 2:
  7.     infile = open(sys.argv[1], 'r')
  8.     for x in infile:
  9.         numLst.append([float(i) for i in x.strip().split()]) 
  10. elif len(sys.argv) <2:
  11.     infilename = raw_input("Name of file: ")
  12.     data = open(infilename, 'r')
  13.     for x in data:
  14.         numLst.append([float(i) for i in x.strip().split()])
  15. elif len(sys.argv) > 2:
  16.     raise SyntaxError, "Too many arguments"
  17. a = array(numLst)
  18. print a
  19. b = a[0:, 1] #this is just me manipulating the list a bit
  20. print b
  21. c = a[0:,1]
  22. print
  23. bA = b[:1]
  24. g = bA
  25. print numLst
  26.  
  27.  
Expand|Select|Wrap|Line Numbers
  1. >>> numList = []
  2. >>> fList = open('data_file').readlines()
  3. >>> for x in fList:
  4. ...     numList.append([float(i) for i in x.strip().split()])
  5. ...     
  6. >>> numList
  7. [[1.0, 2.0], [2.0, 3.5], [2.5, 5.0], [3.5, 6.5]]
  8. >>> 
If you create a file object, don't forget to close it. Done like above, no file object is created.
Apr 11 '07 #12

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Tim Williams | last post by:
I'm trying to write a simple python program to access a MySQL database. I'm having a problem with using MySQLdb to get the results of a SQL command in a cursor. Sometimes the cursor.execute works,...
12
by: Aki Niimura | last post by:
Hello everyone, I started to use pickle to store the latest user settings for the tool I wrote. It writes out a pickled text file when it terminates and it restores the settings when it starts....
1
by: Martin MOKREJ© | last post by:
Hi, is this a bug or "feature" that I have to use float() to make int() autoconvert from it? $ python Python 2.3.4 (#1, Feb 14 2005, 10:00:27) on linux2 Type "help", "copyright", "credits"...
3
by: Pedro Miguel Carvalho | last post by:
Greetings. I have a class that I would like to initialize with a literal array but it is not accepted by the compiler. It works if I use a array variable but not a literal array. Can someone...
3
by: Jon Wilson | last post by:
How do I write Not A Number or +/- infinity (floating point values) as literal constants (I'm using g++)? I have a function that returns float, and I need a flag value, and for various reasons...
0
by: philip20060308 | last post by:
Hi all, Has anyone ever seen Python 2.4.1's httplib choke when reading chunked content? I'm using it via urrlib2, and I ran into a particular server that returns something that httplib doesn't...
2
by: abcd | last post by:
I have the following code which is sent over the wire as a string... from time import time class Foo: def go(self): print "Time:", time() I get this code and store it as, "data"
1
Eclipse
by: Eclipse | last post by:
G'day all In the code below I am trying to catch an error thrown if i enter any other value than an integer. (I used the string 'six' and the float '1.5') The error thrown in the command...
11
by: davidj411 | last post by:
i am parsing a cell phone bill to get a list of all numbers and the total talktime spend on each number. i already have a unique list of the phone numbers. now i must go through the list of...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.