views:

1441

answers:

3

I have a directory full of files, some which have an ampersand in their names. I would like to rename all the files with ampersands and replace each ampersand with a plus (+). I am working with around 10k files. What would be the best method to do this?

+9  A: 
import glob, os
for filename in glob.glob(os.path.join(yourPath, "*&*")):
   os.rename(filename, filename.replace('&','+'))
vartec
iglob would be more suitable here
SilentGhost
Took the liberty to change the string-concatenation into a os.path.join() call, for clarity and portability.
unwind
@SilentGhost -- good point, updated.@unwind -- true, guess I'm to UNIX-centric.
vartec
@vartec: `glob.iglob` is present only in Jython 2.5+ (2.2 lacks it).
J.F. Sebastian
@J.F.Sebastian: reverted change. I guess it won't mater a lot, 10K names, would occupy at most 2,5MB (more like probable something like 100-200KB).
vartec
+1  A: 
import os
directory = '.'
for file in os.listdir(directory):
    if '&' in file :
        os.rename(file, file.replace('&', '+'))

Replace directory with your own path.

sykora
+4  A: 

If you have subdirectories:

import os
for dirpath, dirs, files in os.walk(your_path):
    for filename in files:
        if '&' in filename:
            os.rename(
                os.path.join(dirpath, filename),
                os.path.join(dirpath, filename.replace('&', '+'))
            )
Ali A
What is the point in list comprehension in this case? A simple loop would suffice.
J.F. Sebastian
Does there have to be a point? I might also use a loop here, but the if syntax afterwards seems a bit nicer don't you think?
Ali A
10K list without a reason is the point. Such formatting could lead to bugs e.g., see the comma near `'+')),`.
J.F. Sebastian
jf sebastian, you are right
Ali A
+1: for `os.walk` (though OP asks about *single* directory but in general `os.walk` is preferred).
J.F. Sebastian
btw, jython 2.2 lacks `os.walk` (but jython 2.5 has it).
J.F. Sebastian