Others already demonstrated how to do it. So I'll just suggest better way to get the first word in a string:
filename = "12345 blahblahblah"
sfn = filename.split(" ", 1)
newfilename = sfn[0]
This way if the string doesn't contain " " nothing will happen i.e. the same string will be returned.
Using find(), on the other hand, will return -1 if " " is not found. And, slicing filename[0:-1] would take the last character off, which may be undesirable effect. Both will result in an empty string if first character is " ". So I propose even better solution:
filename = " 12345 blahblahblah"
sfn = filename.split(None, 1)
newfilename = sfn[0]
If some other separator than a whitespace is desired then it would be:
filename = "____12345_blahblahblah"
sfn = [x for x in filename.split("_") if x!=""]
newfilename = sfn[0]
This then would be complete renamer for you. It keeps the extension and respects full paths as well.
import os
def RenameToFirstWord (filename):
filename = os.path.abspath(filename)
origfn = filename
path, filename = os.path.split(filename)
fn, ext = os.path.splitext(filename)
# If filename starts with extension separator (hidden files on *nixes):
if not fn: fn = ext; ext = ""
sfn = fn.split(None, 1)
newfn = sfn[0]+ext
try:
os.rename(origfn, os.path.join(path, newfn))
except Exception, e:
print "Cannot rename '%s' to '%s'!\nError is: '%s'\nand it is ignored!" % (filename, newfn, str(e))