Python脚本:批量修改文件名
问题大致是这样的:我下载了一堆文件放在某个文件夹下,这堆文件的名字都具有这样的格式 [Python乱码哇哇乱码哇哇].Python…. ,于是想把中括号里面的那堆乱码替换掉。
要实现其他字符的替换只需稍稍修改pat这个pattern和sub这个函数就可以了。比如说,要把所有文件名中的字符串A替换成字符串B,那pat和sub就作这样的修改
pat=re.compile(r’A')
re.sub(pat,’B',i)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #! /usr/bin/env python ''' This script is used to substitute all the file name in a directory ''' import shutil import os import re dir=r"/home/yarkee/test/" #The target directory if not os.path.isdir(dir): print "Error: The directory doesn't exist." exit() files=os.listdir(dir) pat=re.compile(r'\[Python.*\]') for i in files: newFile=re.sub(pat,'Python',i) # 'Python' substitute for pat print newFile shutil.move(dir+i,dir+newFile) #Same as the linux command mv |
我们不知道,我们很多都不知道。
http://j.mp/eIZNIv