Really, really annoying problem

Dan Schmidt dfan at harmonixmusic.com
Wed Sep 20 16:22:17 EDT 2000


"Brett Lempereur" <a.lempereur[remove this|@|remove this]cableinet.co.uk> writes:

| Right, well for a start so I don't get everybody on my back again,
| here's the code I'm using...
| 
| [duplicated below]
| 
| The function of this code is to append a filename to the directory
| the module is in, I'll add more functionality later, but for the
| minute this will do.

You probably want to look at the os.path module; I bet it would make
your life a lot easier..  For example, your function below could be
rewritten as follows:

  def addroot (text):
      return os.path.join (os.path.dirname(sys.argv[0]), text)

| Anyway, it does exactly what i want, but unexplainably, instead of
| inserting the one "\" like it should, it inserts "\\" .  I can't
| figure why this is hapenning. and would appreciate anybodies help
| 
| thanks

It works fine for me with Python 1.5.2 on win32:

  import string
  import sys

  def addroot(text):
    # Definitions
    new_string = ""
    arg = sys.argv[0]
    split_arg = string.split(arg, '\\')
    # Cycle through
    for count in range(0, len(split_arg) - 1):
        new_string = new_string + split_arg[count] + "\\"
    new_string = new_string + text
    # Return the reconstructed string
    return new_string

  print addroot(gronk)

  $ python d:\src\py\foo.py
  d:\src\py\gronk

Can you provide a complete program that demonstrates the problem?

My guess is that when you run your program, sys.argv[0] actually has
double backslashes in it, so that every other element of split_arg is
the empty string, so that you get two backslashes in a row when you
try to join it with backslashes.  But that's just a guess.

By the way, if you're interested,

  for count in range(0, len(split_arg) - 1):
    new_string = new_string + split_arg[count] + "\\"
  new_string = new_string + text

is probably more idiomatically written as

  new_string = string.join(split_arg[:-1], "\\") + "\\" + text

There are two changes here:

1) It's often more straightforward to loop directly over the elements
   of the array, instead of over their indices. split_arg[:-1] is all
   the elements of split_arg, starting at 0 and ending at one from the
   end.

2) string.join() already exists for joining lots of strings together
   with a separator, so we use that.

-- 
                 Dan Schmidt | http://www.dfan.org
Honest Bob CD now available! | http://www.dfan.org/honestbob/cd.html



More information about the Python-list mailing list