removing spaces from front and end of filenames

Stephen Horne intentionally at
Sun Jul 13 16:55:27 CEST 2003

On Sat, 12 Jul 2003 21:42:56 -0400, hokiegal99
<hokiegal99 at> wrote:

>This script works as I expect, except for the last section. I want the 
>last section to actually remove all spaces from the front and/or end of 
>filenames. For example, a file that was named "  test  " would be 
>renamed "test" (the 2 spaces before and after the filename removed). Any 
>suggestions on how to do this?


>     for file in files:
>         fname = (file)
>         fname = fname.strip( )
>	print fname

The indentation here looks suspicious. It is a very bad idea to indent
some lines with tabs and others with spaces - use one method or the

Also, you are not saving the stripped versions of the strings

BTW - the strip method doesn't change the object in place, so I don't
see the point of the 'fname = (file)' line. I certainly don't
understand the brackets. In fact, why not just...

  files = [i.strip() for i in files]

My best guess is that you expected the 'file' variable to reference
into the list, but this won't happen - its one of those things that
depends on whether the values are mutable or immutable, and with for
loops it's the type of the items within the list (ie the strings) that
is important. Strings are immutable.

Yes, this mutable/immutable thing is a pain :-(

Anyway, if you don't like list comprehensions, you'll need to loop
through the indices using something like...

  for i in range(len(files)) :
    files[i] = files[i].strip ()

Hope this helps.

More information about the Python-list mailing list