removing spaces from front and end of filenames

hokiegal99 hokiegal99 at hotmail.com
Sun Jul 13 18:43:46 CEST 2003


Ha!!

Fixed it with this bit of code:

for root, dirs, files in os.walk('/home/BradTill/python'):
    for file in files:
        fname = (file)
        fname = fname.strip( )
	newfile = fname
	if newfile:
	    newpath = os.path.join(root,newfile)
            oldpath = os.path.join(root,file)
            os.rename(oldpath,newpath)
	    print oldpath
	    print newpath

Below is a sample of how the script acts on filenames:

--- Remove '%2f' From Filenames ---
 
/home/BradTill/python/  %2fbad%2fmac%2ffile>  
/home/BradTill/python/  -bad-mac-file>  
/home/BradTill/python/-target1-/  %2fbad%2fmac%2ffile|  
/home/BradTill/python/-target1-/  -bad-mac-file|  
/home/BradTill/python/-target1-/-target2-/  %2fbad%2fmac%2ffile?   
/home/BradTill/python/-target1-/-target2-/  -bad-mac-file?   
/home/BradTill/python/-target1-/-target2-/-target3-/ 
%2fbad%2fmac%2ffile\
/home/BradTill/python/-target1-/-target2-/-target3-/  -bad-mac-file\
 
--- Done ---
 
--- Remove Bad Characters From Filenames ---
 
/home/BradTill/python/  -bad-mac-file>  
/home/BradTill/python/  -bad-mac-file-  
/home/BradTill/python/-target1-/  -bad-mac-file|  
/home/BradTill/python/-target1-/  -bad-mac-file-  
/home/BradTill/python/-target1-/-target2-/  -bad-mac-file?   
/home/BradTill/python/-target1-/-target2-/  -bad-mac-file-   
/home/BradTill/python/-target1-/-target2-/-target3-/  -bad-mac-file\
/home/BradTill/python/-target1-/-target2-/-target3-/  -bad-mac-file-
 
--- Done ---
 
--- Remove Spaces From Filenames ---
 
/home/BradTill/python/fix_files.py
/home/BradTill/python/fix_files.py
/home/BradTill/python/fix_dirs.py
/home/BradTill/python/fix_dirs.py
/home/BradTill/python/files
/home/BradTill/python/files
/home/BradTill/python/  -bad-mac-file-  
/home/BradTill/python/-bad-mac-file-
/home/BradTill/python/-target1-/  -bad-mac-file-  
/home/BradTill/python/-target1-/-bad-mac-file-
/home/BradTill/python/-target1-/-target2-/  -bad-mac-file-   
/home/BradTill/python/-target1-/-target2-/-bad-mac-file-
/home/BradTill/python/-target1-/-target2-/-target3-/  -bad-mac-file-
/home/BradTill/python/-target1-/-target2-/-target3-/-bad-mac-file-
 
--- Done ---

Works well on dirs too, except that the path changes when a fix is
made to a parent dir so the script has to be run over and over until
all sub dirs are fixed.




More information about the Python-list mailing list