本帖最后由 疾风怪盗 于 2020-10-10 15:00 编辑
你为什么要写这么复杂,正则是没问题的,能找到,问题出在你的group上,你打印看下 beforePart = mo.group(1)
zeroPart = mo.group(2)
afterPart = mo.group(3)
这三个值是什么。。。。。。。
而且你只要去掉0,为什么不用replace呢?正则其实也用不着的吧。。。。。。。。。import re, os, shutil
# Create a regex that matches files with '0' in the filename.
zeroPattern = re.compile(r'(.*)(0+)(.*)')
# Loop over the files in the working directory.
for filename in os.listdir(r'D:\python\test\1'):
print(filename)
mo = zeroPattern.search(filename)
#Skip file without '0' in the filename.
if mo == None:
continue
zeroFilename=mo.group().replace('0','')
print(zeroFilename)
absWorkingDir = os.path.abspath('.')
filePath = os.path.join(absWorkingDir + '\\' + filename)
zeroFilePath = os.path.join(absWorkingDir + '\\' + zeroFilename)
# Rename the files.
print("Renaming '%s' to '%s'" % (filePath, zeroFilePath))
#shutil.move(filePath, zeroFilePath) # uncomment after test
|