removing spaces from front and end of filenames

Erik Max Francis max at alcyone.com
Sun Jul 13 17:10:33 EDT 2003


hokiegal99 wrote:

> for root, dirs, files in os.walk('/home/rbt/scripts'):
>      for file in files:
>          fname = (file)
>          fname = fname.strip( )
> print fname
> 
> When I print fname, it prints the filenames w/o spaces (a file named "
> test " looks like "test"), but when I ls the actual files in the
> directory they still contain spaces at both ends. That's what I don't
> understand. It seems that .strip is ready to remove the spaces, but
> that it needs one more step to actually do so. Any ideas?

I'm puzzled as to why you find this result confusing.  You're getting a
list of files, and putting their names (as strings) into a variable. 
You're then stripping the spaces from that variable and printing it. 
That doesn't have any effect on the file, because you're manipulating a
string containing the file_name_, not the file itself.  If you want to
rename the file, you need to do something like

	oldFilename = ...
	newFilename = oldFilename.strip()
	os.rename(oldFilename, newFilename)	

-- 
   Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
 __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ Life is a zoo in a jungle.
\__/  Peter de Vries




More information about the Python-list mailing list