spaces at ends of filenames or directory names on Win32

rtilley rtilley at vt.edu
Mon Feb 27 19:01:29 EST 2006


Roel Schroeven wrote:
> rtilley schreef:
> 
>> This will at least allow me to ID folders that start with 
>> whitespace... from within Windows too :) yet I still cannot rename the 
>> folders after stripping the whitespace... attempting to gives an 
>> [Errno 2] No such file or directory. The strip seems to work right too 
>> according to the prints before and after.
> 
> 
> Does the rename work if try with other names? 

Yes, the script can rename files that have no end whitespace. Also, I 
should note the the Windows GUI cannot rename the files. Same error... 
cannot stat the file. The only way I've been able to rename is through 
the cmd prompt using quotes like this:

ren " bad file with end spaces " good_file_no_end_spaces

I should also note that the code I posted earlier is misleading as 
os.listdir() gets dirs and files... not just dirs as I implied. Here's a 
better example that should get whitespace at either end (and does indeed 
on Mac and Unix... but not Windows)

--------------------------------------------------------

import os
import os.path
import string

# dirs is actually files and folders, not just folders.
dirs =  os.listdir(os.getcwd())
path = os.getcwd()
print path

for d in dirs:

     # If folder name begins with whitespace.
     if d[0] in string.whitespace:
         print d
         try:
             new_path = os.path.join(path, d.strip())
             old_path = os.path.join(path, d)
             print new_path
             print old_path
             os.renames(old_path, new_path)
         except Exception, e:
             print e

     # If folder name ends with whitespace.
     elif d[-1] in string.whitespace:
         print d
         try:
             new_path = os.path.join(path, d.strip())
             old_path = os.path.join(path, d)
             print new_path
             print old_path
             os.renames(old_path, new_path)
         except Exception, e:
             print e

     # Folder name is OK, so skip it.
     else:
         pass



More information about the Python-list mailing list