regexp and filenames
emf
i at mindlace.net
Wed Jul 9 00:02:19 EDT 2003
--On 8 Tuesday, July 2003 20:24 -0400 hokiegal99
<hokiegal99 at hotmail.com> wrote:
> I have a bit of a problem that I think Python can solve, but I need a
> bit of direction. I'm replacing 12 Macs with PCs. Macs allow
> characters in filenames that Windows does not, specifically the
> following:
>
> : * ? " < > | / \
>
> I would like to write a script that searches through a directory for
> filenames that contain any of the aboved listed characters and
> replaces them with a - (the minus sign).
>
> I'm familiar with regexp, but I've only used it in Python to act on
> the contents of a file, not filenames in a directory. Any pointers on
> how to approach this are welcome!
>
This should do the trick. You can steal walk from 2.3 and use it in 2.2
with hardly any modifications, if you're using 2.2.
import os, re
# | and \ have to be escaped;
# the r prefix on the string keeps it from being a huge escape:
badcharset = re.compile(r'[*:?"<>/\|\\]')
for root, dirs, files in os.walk('/'): #or however you spell root on
your mac
for file in files:
badchars = badcharset.findall(file)
newfile = ''
for badchar in badchars:
newfile = file.replace(badchar,'-')
if newfile:
newpath = os.path.join(root,newfile)
oldpath = os.path.join(root,file)
os.rename(oldpath,newpath)
Hope that helps,
~mindlace
http://mindlace.net
More information about the Python-list
mailing list