Getting this Python thing down...

Anyone want a copy of my experiment so far? The reason I ask is that I’m not sure of Script posting etiquette. But I wrote a script that loads and saves lines of custom property values to a list from a .txt file and then applies a unique set of three values to an object. I’m sure someone else could find a more ‘Dynamic’ approach but…I’m new to Python.

So if you assign three Custom props (initialized with Blank values) to an object, keep the object on an invisible layer and call for an “addObject” later, the script will find a random string from the list and assign a unique set of properties to the object.
.txt format must go…
Prop1;Prop2;Prop3
Prop1;Prop2;Prop3…etc

Code Goes…

import bge
import bpy
import random
cont = bge.logic.getCurrentController()#need our vars
own = cont.owner
 
anItem = bpy.context.blend_data.object['Object']#UpDate:changed 'object' to 'blend_data.object['Object']'
print(anItem.values())#printing the values of our custom props (Prop1, Prop2, Prop3))
 
items = []#empty list
inF = open("Path", "r")#file stream variable
items = inF.readlines()#get all of it.  We'll sift through it later
inF.close()#don't need it no more
print(items)#Just checking :)
theItem = random.choice(items)#Gimmie a random string from that list
print(theItem)#Just phobic X)
i = theItem.find(';')#find each separator
j = theItem.rfind(';')
k = len(theItem)
anItem['Prop1'] = theItem[0:i]#cherry pick our strings
anItem['Prop2'] = theItem[i:j+1]
anItem['Prop3'] = theItem[j+1:k]
print(anItem.values())#And that's how a bill becomes a law. 8)

I welcome any modifications that I may be too tired to do right now.
As well, will post any updates.

New Blender Users. DONT FORGET TO NAME THE PYTHON CONTROLLER “cont”.:slight_smile:

Just a few tips:

  • Comments should explain why the code is doing something, not what it is doing. Putting a comment saying “file stream variable” next to an “open” statement isn’t conveying anything useful. Saying something like “this is where the items come from” makes more sense.
  • Instead of using “find” and “rfind” to split a string into 3 items at a delimiter, you could use the string “split” method, e.g.
>>> "a;b;c".split(";")
['a', 'b', 'c']
>>> "a;b;c;d".split(";", 2)
['a', 'b', 'c;d']

  • You could bring up a file selector for the user to choose an input file, instead of hard-coding the path.

you could use the string “split” method

Thank you. This is just the kind of feedback I was looking for.

You could bring up a file selector for the user to choose an input file

Not sure about that one. My Kung Fu is not strong enough yet. :slight_smile:

Update: Above I’ve changed the ‘bpy.context.object’ to 'bpy.context.blend_data.object[‘Object’]. Original method only accesses selected object.