I wrote a fast and easy hack to walk thru directories (in stepmania song dir), find conf-files and name the directory the conf-files are in to a certain name found in the conf-file. This works great on my linux box. But not at my wives Windows XP-box running as an admin. I get permission-error. What’s wrong? Here’s the code:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from __future__ import with_statement
import os
import re
import sys
def renamer(in_path):
for (path, dirs, files) in os.walk(in_path):
exts = ['.sm', '.dwi'] # Only search files with this suffix
conf_files = []
# Create list with conf-files
for ext in exts:
conf_files.extend([file for file in files if file.lower().endswith(ext)])
# Search for conf-files in directory
for conf_file in conf_files:
try:
with open(os.path.join(path, conf_file)) as f:
match = re.search('TITLE:\s?(.*);', f.read()) # Search for whatever follows "TITLE:"
new_dir_name = match.group(1) # The new dir-name is whatever the TITLE states in conf-file
os.rename(path, os.path.join(path, '..', new_dir_name))
except IndexError:
print 'No conf-file in', path
if __name__ == '__main__':
path = sys.argv[1].replace('\\', '/') # Windowsify the path
renamer(path)
Windows can’t rename a path that has an open file. It should work if you move the
os.renamecall out of thewithblock so that the file is closed. However, you’re repeating this for multiple files in the same path, and the directory name inpathwill no longer exist after you’ve renamed it. Also,os.walkcan’t traverse subdirectories after you’ve renamed the parent directory.I would check the config files while walking the tree and append
(path, new_path)tuples to a list. Then I’d rename the directories in reverse order.Also,
matchmight beNone, in which case trying to accessmatch.groupwill raise anAttributeError. And Windows system calls seem to handle mixed separators fine in case you want to skip the ‘Windowsify’ step. To clean up a path for printing/logging,os.path.normpathconsistently usesos.path.sepas well as resolving ‘.’ and ‘..’ in a path.