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.