文章来自《Python cookbook》.

翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!

-- 218.25.66.198 [2004-09-29 04:18:46]

1. 描述

Swapping One File Extension for Another Throughout a Directory Tree

改变目录树下某类型文件的类型(名称后缀)

Credit: Julius Welby

1.1. 问题 Problem

You need to rename files throughout a subtree of directories, specifically changing the names of all files with a given extension so that they end in another extension.

需要遍历目录,重命名文件,特别的改变特定类型文件的名称后缀为其他后缀.

1.2. 解决 Solution

Operating throughout a subtree of directories is easy enough, with the os.path.walk function from Python's standard library:

使用os.path.walk标准函数,操作目录树很容易:

   1 import os, string
   2 
   3 def swapextensions(dir, before, after):
   4     if before[:1]!='.': before = '.'+before    #参数合理化
   5     if after[:1]!='.': after = '.'+after       #参数合理化
   6     os.path.walk(dir, callback, (before, -len(before), after))     #"-" ,分块的负值, 如,  stra[-3:], strb[-3:]
   7 
   8 def callback((before, thelen, after), dir, files):
   9     for oldname in files:
  10         if oldname[thelen:]==before:
  11             oldfile = os.path.join(dir, oldname)
  12             newfile = oldfile[:thelen] + after
  13             os.rename(oldfile, newfile)                   #重命名
  14 
  15 if _ _name_ _=='_ _main_ _':
  16     import sys
  17     if len(sys.argv) != 4:
  18         print "Usage: swapext rootdir before after"
  19         sys.exit(100)
  20     swapextensions(sys.argv[1], sys.argv[2], sys.argv[3])

1.3. 讨论 Discussion

This recipe shows how to change the file extensions of (i.e., rename) all files in a specified directory, all of its subdirectories, all of their subdirectories, and so on. This technique is useful for changing the extensions of a whole batch of files in a folder structure, such as a web site. You can also use it to correct errors made when saving a batch of files programmatically.

脚本给出了在指定目录,此目录的子目录,子目录的子目录,即全部目录树下如何改变文件扩展名(重命名)的方法。对于改变整个目录(比如网站)下文件的扩展名,很有用。同时,对于程序产生的具有错误名称的一批文件,也可以使用脚本中的方法进行处理 。

The recipe is usable either as a module, to be imported from any other, or as a script to run from the command line, and it is carefully coded to be platform-independent and compatible with old versions of Python as well as newer ones. You can pass in the extensions either with or without the leading dot (.), since the code in this recipe will insert that dot if necessary.

上面的脚本可以作为一个模块,在程序中引入,或者作为一个命令行脚本使用。脚本具有平台独立性(这是精心编写的代码:)),同时对于Python新旧版本都适用。对于文件名称扩展名前面的".", 脚本作了处理。 传递的参数,包含"." 与否,都可以。

...

1.4. 参考 See Also

The author's web page at http://www.outwardlynormal.com/python/swapextensions.htm.