Python: saving objects's position

(Haunted-House) #1

When I try to save an objects “Position” as a .txt file I get this error:
Type Error: read-only character buffer, list

How can I work around this?
Heres the code:

import GameLogic
GL = GameLogic.getCurrentController()
us = GL.getOwner()

position = us.getPosition()

content = position
file_name = "Position.txt"
save_file = open(file_name, "w")

Please help!

(saluk) #2

The problem is you can only write string data to a file, that is to say TEXT not numbers, or lists or anything else. So convert position to a string first by using the str() function:

position = str(position)

then it will write correctly.

Remember, when you read this information in from the file, you ALSO read it in as a string, not as a list. You have to convert it back into python code using the eval() function the same way you used str(), which will make it a list again.

(Haunted-House) #3

Thanks saluk!!

…How did I forget to change the float list into a string ?..

Puts on the badge of shame :wink:

(saluk) #4

Hehe, we all make silly mistakes some times. Or a lot of the time. (Saluk hides HIS head in shame).


(Ben) #5

-If you import the pickle module you can write all kinds of numbers,string tuples.It 's better especially if you want to read the value from the file later.