批量重命名目录中的文件 [英] Batch Renaming of Files in a Directory

查看:216
本文介绍了批量重命名目录中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种简单的方法来重命名一个目录中已经包含的文件,使用Python?



示例:目录全是* .doc文件,我想以一致的方式重新命名它们。


$ b


X.doc - >new(X) .doc



.doc - >new(Y).doc


解决方案

这种重命名非常简单,例如 os glob 模块:

  import glob,os 

def rename(dir,pattern,titlePattern):
为glob.iglob中的pathAndFilename (os.path.join(dir,pattern)):
title,ext = os.path.splitext(os.path.basename(pathAndFilename))
os.rename(pathAndFilename,
os.path.join(dir,titlePattern%title + ext))

然后你就可以在你的例子中使用它:

  rename(r'c:\ temp \xx',r'*。doc',r'new(%s)')

上面的例子会将 c:\temp\xx dir中的所有 *。doc 文件转换为 new(%s).doc ,其中%s 是文件的前一个基本名称(不带扩展名) p>

Is there an easy way to rename a group of files already contained in a directory, using Python?

Example: I have a directory full of *.doc files and I want to rename them in a consistent way.

X.doc -> "new(X).doc"

Y.doc -> "new(Y).doc"

解决方案

Such renaming is quite easy, for example with os and glob modules:

import glob, os

def rename(dir, pattern, titlePattern):
    for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):
        title, ext = os.path.splitext(os.path.basename(pathAndFilename))
        os.rename(pathAndFilename, 
                  os.path.join(dir, titlePattern % title + ext))

You could then use it in your example like this:

rename(r'c:\temp\xx', r'*.doc', r'new(%s)')

The above example will convert all *.doc files in c:\temp\xx dir to new(%s).doc, where %s is the previous base name of the file (without extension).

这篇关于批量重命名目录中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆