2013-12-12 50 views
3

我试图在rename()之外定义arg1,它不起作用,因为dirs未定义。如果我使用rename("dirs", False),该功能不起作用。递归地重命名本地文件系统上的目录/文件结构

有什么想法?

# Defining the function that renames the target 
def rename(arg1, arg2): 
    for root, dirs, files in os.walk(   # Listing 
     path, topdown=arg2): 
     for i, name in enumerate(arg1): 
      output = name.replace(pattern, "") # Taking out pattern 
      if output != name: 
       os.rename(      # Renaming 
        os.path.join(root, name), 
        os.path.join(root, output)) 
      else: 
       pass 

# Run 
rename(dirs, False) 

这里的整个程序:

#!/usr/bin/python 
# -*- coding: utf-8 -*- 

# This program batch renames files or folders by taking out a certain pattern 

import os 
import subprocess 

import re 

# Defining the function that renames the target 
def rename(arg1, arg2): 
    for root, dirs, files in os.walk(   # Listing 
     path, topdown=arg2): 
     for i, name in enumerate(arg1): 
      output = name.replace(pattern, "") # Taking out pattern 
      if output != name: 
       os.rename(      # Renaming 
        os.path.join(root, name), 
        os.path.join(root, output)) 
      else: 
       pass 


# User chooses between file and folder 
print "What do you want to rename?" 
print "1 - Folders\n2 - Files\n" 
valid = False 
while not valid: 
    try: 
     choice = int(raw_input("Enter number here: ")) 
     if choice > 2: 
      print "Please enter a valid number\n" 
      valid = False 
     else: 
      valid = True 
    except ValueError: 
     print "Please enter a valid number\n" 
     valid = False 
     choice = 3 # To have a correct value of choice 

# Asking for path & pattern 
if choice == 1: 
    kind = "folders" 
elif choice == 2: 
    kind = "files" 
else: 
    pass 
path = raw_input("What is the path to the %s?\n " % (kind)) 
pattern = raw_input("What is the pattern to remove?\n ") 

# CHOICE = 1 
# Renaming folders 
if choice == 1: 
    rename(dirs, False) 

# CHOICE = 2 
# Renaming files 
if choice == 2: 
    rename(files,True) 

# Success message 
kind = kind.replace("f", "F") 
print "%s renamed" % (kind) 
+2

什么是你_trying_办? –

+0

您能否提供一个您尝试重命名的目录结构示例?我怀疑有一个更好的方法来处理你想要做的事... –

+0

整个程序更清晰吗? – baldurmen

回答

2

Recorrect我的代码以更好的方式。

#!/usr/bin/env python 

import os 
import sys 


# the command like this: python rename dirs /your/path/name/ tst 
if __name__ == '__main__': 
    mode = sys.argv[1] # dirs or files 
    pathname = sys.argv[2] 
    pattern = sys.argv[3] 

    ndict = {'dirs': '', 'files': ''} 
    topdown = {'dirs': False, 'files': True} 

    for root, ndict['dirs'], ndict['files'] in os.walk(
      pathname, topdown[mode]): 
     for name in enumerate(ndict[mode]): 
      newname = name.replace(pattern, '') 
      if newname != name: 
       os.rename(
        os.path.join(root, name), 
        os.path.join(root, newname)) 
+0

我不同意。这是次优的,并且不清楚发生了什么。重新使用已经实现并为常见用例提供良好功能的库更好(*除非您正在尝试了解它是如何完成的*)。 –

+0

你的“变化”也有错误,未经测试:/“路径”从哪里来?这可能会抛出一个''NameError'' –

+0

@JamesMills是的,你的回答非常正确,并且你重写了提供者的整个代码。并且我只改进需要修正的“提供的代码提供者”,以使程序运行。所以我认为我仍然需要向您学习,不仅纠正代码出错的地方,还要以更合适的方式整理代码。 – stupidgrass

2

这是更好地实现与使用py库中的命令行工具:

import sys 


from py.path import local # import local path object/class 


def rename_files(root, pattern): 
    """ 
    Iterate over all paths starting at root using ``~py.path.local.visit()`` 
    check if it is a file using ``~py.path.local.check(file=True)`` and 
    rename it with a new basename with ``pattern`` stripped out. 
    """ 

    for path in root.visit(rec=True): 
     if path.check(file=True): 
      path.rename(path.new(basename=path.basename.replace(pattern, ""))) 


def rename_dirs(root, pattern): 
    """ 
    Iterate over all paths starting at root using ``~py.path.local.visit()`` 
    check if it is a directory using ``~py.path.local.check(dir=True)`` and 
    rename it with a new basename with ``pattern`` stripped out. 
    """ 

    for path in root.visit(rec=True): 
     if path.check(dir=True): 
      path.rename(path.new(basename=path.basename.replace(pattern, ""))) 


def main(): 
    """Define our main top-level entry point""" 

    root = local(sys.argv[1]) # 1 to skip the program name 
    pattern = sys.argv[2] 

    if local(sys.argv[0]).purebasename == "renamefiles": 
     rename_files(root, pattern) 
    else: 
     rename_dirs(root, pattern) 


if __name__ == "__main__": 
    """ 
    Python sets ``__name__`` (a global variable) to ``__main__`` when being called 
    as a script/application. e.g: Python renamefiles or ./renamefiles 
    """ 

    main() # Call our main function 

用法:

renamefiles /path/to/dir pattern 

或:

renamedirs /path/to/dir pattern 

保存为renamefilesrenamedirs。 在UNIX中的一种常用方法是命名脚本/工具renamefiles和符号链接renamefilesrenamedirs

改进注:

  • 使用optparse或​​提供命令行选项=和--help
  • rename_files()和通用rename_dirs()并将其移动到一个单一的功能。
  • 写文档(文档字符串
  • 写单元测试。
+0

詹姆斯·米尔斯1 baldurmen 0 感谢队友,这是非常好的(甚至想到了我的自我说“outch”:d) – baldurmen

+1

@baldurmen不客气。我只是希望这不是一个学校/大学的任务,我只是为你解决它:) - 我希望这将是一个普遍有用的工具给别人! –

+0

Naaa,只是我鬼混学python – baldurmen

相关问题