递归地重命名本地文件系统上的目录/文件结构

时间:2013-12-12 05:25:55

标签: python

我正在尝试在arg1之外定义rename(),但由于未定义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 个答案:

答案 0 :(得分: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和符号链接renamefiles命名为renamedirs

改进说明:

  • 使用optparseargparse提供命令行选项=和--help
  • rename_files()rename_dirs()设为通用,并将其移至单个函数中。
  • 编写文档( docstrings
  • 编写单元测试。

答案 1 :(得分:2)

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

#!/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))
相关问题