2011-11-06 67 views
1

我写了一个快速简单的hack来遍历目录(在stepmania的歌曲目录中),找到conf文件并将conf文件所在的目录命名为conf文件中的某个名称。这对我的linux系统非常有用。但不是在我的妻子Windows XP中作为管理员运行。我得到许可错误。怎么了?这里是代码:Windows中的路径和权限



#!/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) 


回答

1

Windows无法重命名具有打开文件的路径。如果您将os.rename呼叫从with块中移出,以便该文件关闭,它应该可以工作。但是,您对同一路径中的多个文件重复此操作,并且在重命名后,path中的目录名称将不再存在。此外,在重命名父目录后,os.walk无法遍历子目录。

我会在走树时检查配置文件并将(path, new_path)元组添加到列表中。然后我会以相反的顺序重命名目录。

另外,match可能是None,在这种情况下尝试访问match.group将引发AttributeError。如果您想跳过“Windowsify”步骤,Windows系统调用似乎可以处理混合分隔符。要清理打印/日志记录的路径,os.path.normpath始终使用os.path.sep以及解决'。'和'..'在路径中。

+0

哦,这很有道理。我会马上开始编码! :-) –

+0

我做到了。非常感谢! :) –

0

你忘了在路径上放一个盘符,如C:\?在代码最底部打印出path的值,看看它是否能够让你直接粘贴到Windows文件浏览器中。

+0

这似乎是正确的。在重命名(路径)之前的“打印路径”返回c:/ traningspass(据我所知,这是正确的) –