Python批量重命名文件方法很简单我们会利用listdir与rename 再加上目录遍历即可实现文件重命令了,下面整理了一些方法。
用到了os的两个接口:
1、列出文件夹中的所有文件(也包含目录)
os.listdir(path)
Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.
Availability: Unix, Windows.
Changed in version 2.3: On Windows NT/2k/XP and Unix, if path is a Unicode object, the result will be a list of Unicode objects. Undecodable filenames will still be returned as string objects
2、对文件进行重命名
os.rename(src, dst)
Rename the file or directory src to dst. If dst is a directory, OSError will be raised. On Unix, if dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if dst already exists, OSError will be raised even if it is a file; there may be no way to implement an atomic rename when dst names an existing file.
Availability: Unix, Windows
代码如下 | |
import os dirpath="D:/workbench/crazyant.net/myfiles" for fname in os.listdir(dirpath): newfname=fname[3:] newfpath="%s/%s"%(dirpath,newfname) oldfpath="%s/%s"%(dirpath,fname) os.rename(oldfpath, newfpath) |
其实就是用os.listdir读取里面所有的文件,然后用os.rename进行文件重命名即可实现
3、对于上面的办法我还找到一些方法
代码如下 | |
# coding=utf-8 import os import re path = "D:temp" pattern = re.compile('d{3}') for file in os.listdir(path): if os.path.isfile(os.path.join(path, file)): match = pattern.search(file) assert match name = match.group() + '.mp3' #print file, name os.rename(os.path.join(path, file), os.path.join(path, name)) |
要注意match和search的区别:match是从头开始匹配,search就是贪心。其实也没这么复杂有一个叫Bulk Rename Utility的玩意儿就是拿来重命名用的。
再补充一个
输入指定目录,程序处理该目录及其包含有big.jpg文件的子目录,
将名称类似’big(5).jpg’的文件改名为’big_5.jpg’,
即 big(N).jpg ==> big_N.jpg
代码如下:
# coding: cp936
"""
文件重命名
输入指定目录,程序处理该目录及其包含有big.jpg文件的子目录,
将名称类似'big(5).jpg'的文件改名为'big_5.jpg',
即 big(N).jpg ==> big_N.jpg
@author chenwei
@date 2010-12-26
"""
import glob
import os
def main():
print '重命名任务开始'
base_dir = raw_input('请输入待处理目录:')
# 处理顶级目录
rename_dir(base_dir)
# 查找包含有big.jpg文件的子目录
pattern = base_dir + r'*big.jpg'
file_list = glob.glob(pattern)
# 对各目录分别进行处理
for file in file_list:
i = file.rindex('')
dir = file[:i]
rename_dir(dir)
print '重命名任务完成'
raw_input('输入任意内容结束')
def rename_dir(dir):
# 根据模式查找待改名的文件
pattern = dir + r'big(*).jpg'
file_list = glob.glob(pattern)
# 分别处理各文件
for file in file_list:
rename_file(file)
def rename_file(fname):
# 取得文件名,去除路径及扩展名
i = fname.rindex('')
j = fname.rindex('.')
basename = fname[i+1:j]
# 获取文件编号
k = basename.rindex('(')
l = basename.rindex(')')
seq = basename[k+1:l]
# 新文件名
new_fname = fname.replace(fname[i+1:j], 'big_'+seq)
# 重命名
try:
os.rename(fname, new_fname)
print '重命名 ' + fname + ' to ' + new_fname + ' 成功'
except:
print '重命名 ' + fname + ' to ' + new_fname + ' 失败'
if __name__ == '__main__':
main()