| 
 | 
 
 
发表于 2020-10-10 15:03:30
|
显示全部楼层
 
 
 
 
按你的写法的话,加个\D试试 
- import re, os, shutil
 
  
- # Create a regex that matches files with '0' in the filename.
 
 - zeroPattern = re.compile(r'(.\D*)(0+)(.*)')
 
  
- #我的目的是为了把abd001.txt和agsad01.txt分别改为abd1.txt和agsad1.txt。但是我的代码只能改为abd01.txt和agsad1.txt)
 
  
- # 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
 
 -     print(mo)
 
 -     # Get the different parts of the filename.
 
 -     beforePart = mo.group(1)
 
 -     zeroPart   = mo.group(2)
 
 -     afterPart  = mo.group(3)
 
 -     print('1'+beforePart,zeroPart,afterPart)
 
  
-     # Form the filename without '0'.
 
 -     zeroFilename = beforePart + afterPart
 
  
-     # Get the full, absolute file paths.
 
 -     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
 
  复制代码 
 
abd001.txt 
<re.Match object; span=(0, 10), match='abd001.txt'> 
1abd 00 1.txt 
Renaming 'D:\python\test\abd001.txt' to 'D:\python\test\abd1.txt' 
agsad01.txt 
<re.Match object; span=(0, 11), match='agsad01.txt'> 
1agsad 0 1.txt 
Renaming 'D:\python\test\agsad01.txt' to 'D:\python\test\agsad1.txt' |   
 
 
 
 |