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
2009-03-13 09:58:43
iglob would be more suitable here
SilentGhost
2009-03-13 11:47:03
Took the liberty to change the string-concatenation into a os.path.join() call, for clarity and portability.
unwind
2009-03-13 11:47:08
@SilentGhost -- good point, updated.@unwind -- true, guess I'm to UNIX-centric.
vartec
2009-03-13 12:09:31
@vartec: `glob.iglob` is present only in Jython 2.5+ (2.2 lacks it).
J.F. Sebastian
2009-03-13 12:19:57
@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
2009-03-13 12:29:59
+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
2009-03-13 10:23:09
+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
2009-03-13 11:42:25
What is the point in list comprehension in this case? A simple loop would suffice.
J.F. Sebastian
2009-03-13 11:58:18
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
2009-03-13 12:10:45
10K list without a reason is the point. Such formatting could lead to bugs e.g., see the comma near `'+')),`.
J.F. Sebastian
2009-03-13 12:24:18
+1: for `os.walk` (though OP asks about *single* directory but in general `os.walk` is preferred).
J.F. Sebastian
2009-03-14 10:35:15