ValueError: could not convert string to float: - string

I have a problem with the following code:
inputf = open('test.dat', 'r')
lines = inputf.readlines()
rico_clus_e = []
for line in lines:
line.split()
print line
if (line[0] != '#'):
rico_clus_e.append(float(line[4]))
inputf.close()
My test.dat file is:
# specn rico_all rico_all_e rico_clus rico_clus_e rico_farclust rico_far_e extin
a119 1.07038692 0.11109547 0.61473431 0.15063627 0.32590239 0.14777812 0.207
And this gives the following output in my terminal:
# specn rico_all rico_all_e rico_clus rico_clus_e rico_farclust rico_far_e extin
a119 1.07038692 0.11109547 0.61473431 0.15063627 0.32590239 0.14777812 0.207
Traceback (most recent call last):
File "test.py", line 8, in <module>
rico_clus_e.append(float(line[4]))
ValueError: could not convert string to float:
I'm quite confused by this. It had nothing to do with spaces, I checked them all. And if you change 4 by 1, 2 or 3 this works, so it must have something to do with the test.dat file, but I can't seem to figure out how. I'm using python 2.7.3.

line.split() on its own does nothing to line. You must store the result of the method call and use that instead.

Related

Reading input after reading stdin throws EOFerror

I'm trying to read a string from stdin and have the user make a selection. After reading the input from stdin and prompting the user for a selection I receive the following error:
Traceback (most recent call last):
File "/media/Projects/MetaMusic/test.py", line 6, in <module>
b = input(a + ":")
EOFError: EOF when reading a line
Src:
import sys
for line in sys.stdin:
a = line
break
b = input(a + ":")
I've tried multiple different ways of getting the string but I receive the same error.

How do I fix this EOF error on python 3 version

I am working on a very basic problem on Hackerrank.
Input format:
First line contains integer N.
Second line contains string S.
Output format:
First line should contain N x 2.
Second line should contain the same string S.
sample test case
5
helloworld
my code is as: (on PYTHON 3)
n=int(input())
s=input()
print(2*n)
print(s)
I am getting error:
Execution failed.
EOFError : EOF when reading a line
Stack Trace:
Traceback (most recent call last):
File "/tmp/143981299/user_code.py", line 1, in <module>
N = int(input())
EOFError: EOF when reading a line
I tried this method to take input many times and this is the first time I am having this error. Can anyone please explain why?
use a try/except block to handle the error
while True:
try:
n=int(input())
s=input()
print(2*n)
print(s)
except:
break

New line on error message in KeyError - Python 3.3

I am using Python 3.3 through the IDLE. While running a code that looks like:
raise KeyError('This is a \n Line break')
it outputs:
Traceback (most recent call last):
File "test.py", line 4, in <module>
raise KeyError('This is a \n Line break')
KeyError: 'This is a \n Line break'
I would like it to output the message with the line break like this:
This is a
Line Break
I have tried to convert it to a string before or using os.linesep but nothing seems to work. Is there any way I can force the message to be correctly shown on the IDLE?
If I raise an Exception (instead of KeyError) then the output is what I want, but I would like to still raise a KeyError if possible.
You problem has nothing to do with IDLE. The behavior you see is all from Python. Running current repository CPython interactively, from a command line, we see the behavior you reported.
Python 3.7.0a2+ (heads/pr_3947:01eae2f721, Oct 22 2017, 14:06:43)
[MSC v.1900 32 bit (Intel)] on win32
>>> raise KeyError('This is a \n Line break')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'This is a \n Line break'
>>> s = 'This is a \n Line break'
>>> s
'This is a \n Line break'
>>> print(s)
This is a
Line break
>>> raise Exception('This is a \n Line break')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception: This is a
Line break
>>> raise IndexError(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: This is a
Line break
>>> try:
... raise KeyError('This is a \n Line break')
... except KeyError as e:
... print(e)
'This is a \n Line break'
>>> try:
... raise KeyError('This is a \n Line break')
... except KeyError as e:
... print(e.args[0])
This is a
Line break
I don't know why KeyError acts differently from even IndexError, but printing e.args[0] should work for all exceptions.
EDIT
The reason for the difference is given in this old tracker issue, which quotes a comment in the KeyError source code:
/* If args is a tuple of exactly one item, apply repr to args[0].
This is done so that e.g. the exception raised by {}[''] prints
KeyError: ''
rather than the confusing
KeyError
alone. The downside is that if KeyError is raised with an
explanatory
string, that string will be displayed in quotes. Too bad.
If args is anything else, use the default BaseException__str__().
*/
This section appears in the KeyError_str object definition in Objects/exceptions.c of the Python source code.
I will mention your issue as another manifestation of this difference.
There is a way to get the behavior you want: Simply subclass str and override __repr__:
class KeyErrorMessage(str):
def __repr__(self): return str(self)
msg = KeyErrorMessage('Newline\nin\nkey\nerror')
raise KeyError(msg)
Prints:
Traceback (most recent call last):
...
File "", line 5, in
raise KeyError(msg)
KeyError: Newline
in
key
error

Contradicting Errors?

So I'm trying to edit a csv file by writing to a temporary file and eventually replacing the original with the temp file. I'm going to have to edit the csv file multiple times so I need to be able to reference it. I've never used the NamedTemporaryFile command before and I'm running into a lot of difficulties. The most persistent problem I'm having is writing over the edited lines.
This part goes through and writes over rows unless specific values are in a specific column and then it just passes over.
I have this:
office = 3
temp = tempfile.NamedTemporaryFile(delete=False)
with open(inFile, "rb") as oi, temp:
r = csv.reader(oi)
w = csv.writer(temp)
for row in r:
if row[office] == "R00" or row[office] == "ALC" or row[office] == "RMS":
pass
else:
w.writerow(row)
and I get this error:
Traceback (most recent call last):
File "H:\jcatoe\Practice Python\pract.py", line 86, in <module>
cleanOfficeCol()
File "H:\jcatoe\Practice Python\pract.py", line 63, in cleanOfficeCol
for row in r:
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
So I searched for that error and the general consensus was that "rb" needs to be "rt" so I tried that and got this error:
Traceback (most recent call last):
File "H:\jcatoe\Practice Python\pract.py", line 86, in <module>
cleanOfficeCol()
File "H:\jcatoe\Practice Python\pract.py", line 67, in cleanOfficeCol
w.writerow(row)
File "C:\Users\jcatoe\AppData\Local\Programs\Python\Python35-32\lib\tempfile.py", line 483, in func_wrapper
return func(*args, **kwargs)
TypeError: a bytes-like object is required, not 'str'
I'm confused because the errors seem to be saying to do the opposite thing.
If you read the tempfile docs you'll see that by default it's opening the file in 'w+b' mode. If you take a closer look at your errors, you'll see that you're getting one on read, and one on write. What you need to be doing is making sure that you're opening your input and output file in the same mode.
You can do it like this:
import csv
import tempfile
office = 3
temp = tempfile.NamedTemporaryFile(delete=False)
with open(inFile, 'r') as oi, tempfile.NamedTemporaryFile(delete=False, mode='w') as temp:
reader = csv.reader(oi)
writer = csv.writer(temp)
for row in reader:
if row[office] == "R00" or row[office] == "ALC" or row[office] == "RMS":
pass
else:
writer.writerow(row)

Am having difficulties with unicode strings serialport.write("\x23o0 \x23f") not being supported

We are having difficulty with the following code
#Get the heading from the IMU
#Translate the IMU from magnetic north to true north since the calcs use true north
def getcurheading():
# The escape character for # is \x23 in hex
serialport.write("\x23o0 \x23f")
headresponse = serialport.readline()
# print(headresponse)
words = headresponse.split(",")
if len(words) > 2:
try:
curheading = (float(words[0])) + 180
if curheading + Declination > 360: curheading = curheading - 360 + Declination
else: curheading = curheading + Declination
except:
curheading = 999
# print(curheading)
return curheading
Here is the error reported:
Traceback (most recent call last):
File "solarrobot7-core.py", line 256, in <module>
if (getcurheading() < getsolarheading()) and (getsolarangle() > 2) and (getcurheading() != 999):
File "solarrobot7-core.py", line 118, in getcurheading
serialport.write("\x23o0 \x23f")
File "/usr/local/lib/python3.2/dist-packages/serial/serialposix.py", line 518, in write
d = to_bytes(data)
File "/usr/local/lib/python3.2/dist-packages/serial/serialutil.py", line 58, in to_bytes
raise TypeError('unicode strings are not supported, please encode to bytes: %r' % (seq,))
TypeError: unicode strings are not supported, please encode to bytes: '#o0 #f'
It looks like i can use:
a_string = '\x23o0 \x23f Python'
by = a_string.encode('utf-8')
serialport.write(“\x23o0 \x23f “) a serialport.write(by)
Is this correct? Since i'm not a coder i'm not sure if this fix is correct. i've tried it and the code continues until it throws another error which appears to be related to this step. This is why we're backtracking to see if this is correct before moving on.
In Python 3.X, strings such as "abc" by default are Unicode strings. Strings must be encoded for transmission, or just start with a byte string b"abc" (note the b). Either of these will work:
serialport.write(b"\x23o0 \x23f")
or:
serialport.write("\x23o0 \x23f".encode('ascii'))
Note that specifying an encoding is optional and defaults to utf8.
bytearray is a mutable form of a byte string and isn't really needed here. It should have given you an error without an encoding on Python 3:
>>> bytearray("abc")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string argument without an encoding
>>> bytearray("abc",'ascii')
bytearray(b'abc')
You can edit bytearrays:
>>> bytes = bytearray("abc",'ascii')
>>> bytes[1]=50
>>> bytes
bytearray(b'a2c')
but not byte strings:
>>> bytes = b'abc'
>>> bytes[1] = 50
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'bytes' object does not support item assignment

Resources