[CLUE-Tech] removing spaces from filenames?
Matt Gushee
mgushee at havenrock.com
Sun Nov 17 14:52:46 MST 2002
On Sun, Nov 17, 2002 at 01:14:22PM -0700, Dave Price wrote:
>
> I have a _bunch_ of files that were created on a windoze system with
> embedded spaces in their names. Can anyone recommend a technique to
> programmatically rename the files - replacing ' ' with '_' on both the
> file and dir names?
>
> I am thinking perl, but I am not sure what sysntax I would need to use
> to search and rename.
Well, IANAPH (I Am Not A Perl Hacker), but here's how you would do it in
Python:
#!/usr/bin/env python
import os, string
# This is untested, so back up your stuff first!
# Also, I'm assuming you want it to be recursive.
# Should work for all directories, regular files, and
# symlinks. Could raise unhandled exception in case of
# sockets, device files, or anything unwritable.
#
# Usage: <script_name> <directory>
def space2_(dir):
contents = os.listdir(dir)
for i in range(len(contents)):
contents[i] = os.path.join(dir,contents[i])
subdirs = filter(lambda f: os.path.isdir(f), contents)
for s in subdirs:
space2_(s)
for f in contents:
newname = string.replace(f, ' ', '_')
os.rename(f, newname)
## This 'if' statement detects that the current module is being invoked
## directly (rather than imported as a library).
if __name__ == '__main__':
import sys
# Probably should have exception handling, but this is a quick 'n'
# dirty script.
start_dir = sys.argv[1]
space2_(start_dir)
--
Matt Gushee When a nation follows the Way,
Englewood, Colorado, USA Horses bear manure through
mgushee at havenrock.com its fields;
http://www.havenrock.com/ When a nation ignores the Way,
Horses bear soldiers through
its streets.
--Lao Tzu (Peter Merel, trans.)
More information about the clue-tech
mailing list