Windows中的路径和权限

时间:2011-11-06 13:44:51

标签: python windows

我写了一个快速简单的黑客来通过目录(在stepmania song dir中),查找conf文件并将conf文件所在的目录命名为conf文件中的某个名称。这在我的linux机箱上运行得很好。但不是在我的妻子Windows XP-box作为管理员运行。我得到了许可错误。怎么了?这是代码:



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


2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

您是否忘记在路径上添加驱动器号,例如C:\?在代码的最底部打印path的值,看看它是否为您提供了可以直接粘贴到Windows文件资源管理器中的内容。

相关问题