Cannot parse strings from list into floats, getting ValueError - python

I am writing short pygame script and I need to parse values from .cfg file, but I am not very experienced in python and I am getting ValueError and have no idea why it cannot parse the string.
I have tried writing a method to take the string and convert it to an int, if it fails convert it to float but that didn't work.
Here's the code:
def _file_read(self):
with open(os.path.join(sys.path[0], "planets.cfg")) as config:
lines = [line.replace(';', '').replace('{', '').replace('}', '').split() for line in config]
for j in range(len(lines)):
self.name.append(lines[j][0])
self.radius.append(float(lines[j][1]))
self.distance.append(float(lines[j][2]))
self.speed.append(float(lines[j][3]))
self.color.append(lines[j][4])
Here is what is inside the planets.cfg file, don't mind the values, they are made up for testing purposes.
Earth {123; 321; 0.005; (0,255,0)}
Mars {432; 234; 0.004; (255,0,0)}
I need to have a float that I can pass to a mathematical formula, but the ValueError likes the floats place a bit more.
Any idea how to handle that? I will be very grateful for any help or explanation why this error happens :)
Oh and here is the error it outputs:
File "C:/Users/Jakub/PycharmProjects/untitled/kruznice.py", line 35 in _file_read
self.radius.append(float(lines[j][1])) ValueError: could not convert string to float: 'radius'
EDIT Added error message, yeah, I am a really scatterbrained person.
EDIT #2 (Solution): So after a while I found the solution and it basically has NOTHING to do with code being wrong. I have had string values on line 2 in the planets.cfg file and somehow I forgot to save it, and was constantly thinking I am using the newer version with integers and floats only. Yes. Stupid mistakes happen. And I make lot of them.

The error is from self.color.append(float(lines[j][4])) You are trying to convert a tuple to float
Use ast module to convert it to a tuple
Ex:
from ast import literal_eval
def _file_read(self):
with open(os.path.join(sys.path[0], "planets.cfg")) as config:
lines = [line.replace(';', '').replace('{', '').replace('}', '').split() for line in config]
for j in lines:
self.name.append(j[0])
self.radius.append(float(j[1]))
self.distance.append(float(j[2]))
self.speed.append(float(j[3]))
self.color.append(literal_eval(j[4]))

Related

How to save a print output with 'for' loop as an array variable in Python?

I have a bigger script where at the end I need to change string variable to the binary code. It works and it prints binary code for the given string. I would like to save that binary code as a variable, preferable for example as an array - one char into one position. Unfortunately, no solution came to my mind that would work. I checked several threads about saving print outputs to the variables, but it seems that with the code that I have nothing works properly.
Code below:
import numpy as np
str = "sample"
print(" ".join(f"{ord(i):08b}" for i in str))
Things that obviously are not working:
[1] this = print(" ".join(f"{ord(i):08b}" for i in str))
[2] this = np.array(print(" ".join(f"{ord(i):08b}" for i in str)))
In the [2] case it doesn't give any error and the variable is saved, but the content of the variable is "ndarray object of numpy module". When I want to open it I see message "object arrays are currently not supported".
Is there any simple solution to this?
Thank you!
print() returns None. Since you don't want to write anything to sys.stdout, you should remove that. Something like this:
this = np.array(' '.join(format(ord(i), 'b') for i in str))
You can even convert it to a bytearray:
this = np.array(' '.join(format(x, 'b') for x in bytearray(st)))
Using format(...) makes more sense here. The 'b' is for binary.
Hope this helps. Good luck.

My String Is Not Converting to a Float and I have No Idea Why

I'm importing some text files and trying to plot some data, however, I keep getting the error message:
ValueError: could not convert string to float:
Here's the portion of my code that's giving me trouble. Do you see any issues with this?
Thank you!
import matplotlib.pyplot as plt
import numpy as np
import pylab
fluxdensity = []
days= []
with open('knowniaxflux.csv') as f:
for row in f.readlines():
row.strip('\n')
if not row.startswith("#"):
spaces = row.split(',')
fluxdensity.append(float(spaces[0]))
days.append(float(spaces[1]))
You're probably just not getting the input you expect. You should use print statements to see what you're actually trying to convert (While debugging, of course. Remove them later).
In addition, unless you know exactly how your input looks like, you probably need a more solid parser anyways. For example #'s might not be the first character in the file. You might want to specify an encoding to the file (unless you're always using ASCII/UTF-8 (PY2/PY3) anyways.). You might also want to strip spaces if you expect any.
If all else fails, in my experience your file is written in the wrong encoding. Make sure your file is written using one of the encodings mentioned above, and preferably convert you binary input to Unicode format (especially if you're using PY3. That would be the str object). Read the Python Unicode HOWTO, it should make it all clear.

Explicit float conversion in python gives ParseError

I'm learning python in Coursera, I tried the assignment for the course but am not getting the desired result. This program is supposed to extract '0.8475' and convert it to float before printing it.
text = "X-DSPAM-Confidence: 0.8475";
pos=text.find('0');
s=text[pos:len(text)];
p=0.0;
p=(float)s;
print p;
Everytime I run this code, I get a ParseError: bad input on line 5.
What am I doing wrong?
As #ZdaR mentions, the call to the float function must pass the parameter inside the parentheses as p = float(s). I tested this in Python IDLE and the program worked correctly.
Also note that you should not end lines with ; in Python. The whitespace itself will handle that for you when you start a new line.

Base64 string format in python

I'm having an issue figuring out how to properly input base64 data into a string format in python 2.7. Here's the relevant code snippet:
fileExec = open(fileLocation, 'w+')
fileExec.write(base64.b64decode('%s')) %(encodedFile) # encodedFile is base64 data of a file grabbed earlier in the script.
fileExec.close()
os.startfile(fileLocation)
As silly as it may seem, I am required to use the string formatting in this case, due to the what this script is actually doing, but when I launch the script, I receive the following error:
TypeError: Incorrect Padding
I'm not quite sure what I need to do to the '%s' to get this to work. Any suggestions? Am I using the wrong string format?
Update: Here's a better idea of what I'm ultimately trying to accomplish:
encodedFile = randomString() # generates a random string for the variable name to be written
fileExec = randomString()
... snip ...
writtenScript += "\t%s.write(base64.b64decode(%s))\n" %(fileExec, encodedFile) # where writtenScript is the contents of the .py file that we are dynamically generating
I must use string formatting because the variable name will not always be the same in the python file we making.
That error usually means your base64 string may not be encoded properly. But here it is just a side-effect of a logic error in your code.
What you have done is basically this:
a = base64.b64decode('%s')
b = fileExec.write(a)
c = b % (encodedFile)
So you are attempting to decode the literal string "%s", which fails.
It should look more like this:
fileExec.write(base64.b64decode(encodedFile))
[edit: using redundant string format... pls don't do this in real code]
fileExec.write(base64.b64decode("%s" % encodedFile))
Your updated question shows that the b64decode part is inside of a string, not in your code. That is a significant difference. The code in your string is also missing a set of inner quotes around the second format:
writtenScript += "\t%s.write(base64.b64decode('%s'))\n" % (fileExec, encodedFile)
(notice the single quotes...)

Write Number as string csv python

I'm trying to write a csv file from json data. During that, i want to write '001023472' but its writing as '1023472'. I have searched a lot. But dint find an answer.
The value is of type string before writing. The problem is during writing it into the file.
Thanks in advance.
Convert the number to string with formatting operator; in your case: "%09d" % number.
Use the format builtin or format string method.
>>> format(1023472, '09')
'001023472'
>>> '{:09}'.format(1023472)
'001023472'
If your "number" is actually a string, you can also just left-pad it with '0''s:
>>> format('1023472', '>09')
'001023472'
The Python docs generally eschew % formatting, saying it may go away in the future and is also more finnicky; for new code there is no real reason to use it, especially in 2.7+.

Categories