9.4项目第4步中的练习,只做了1, 3题
9.4.1
import os, shutil
# Loop over the file in the working directory.
for filename in os.listdir():
preFilename = 'duke_' + filename
# Get the full, absolute file paths.
absWorkingDir = os.path.abspath('.')
filePath = os.path.join(absWorkingDir + '\\' + filename)
preFilePath = os.path.join(absWorkingDir + '\\' + preFilename)
# Rename the files.
print("Rename '%s' to '%s'..." % (filePath, preFilePath))
#shutil.move(filePath, preFilePath) # uncomment after test
9.4.3
在写正则表达式时,我刚开始用的是re.compile(r'^(.*)(0+)(.*)$'),可是这样总是只把文件名中需要删除的‘0’中的一个删除,剩下的依然存在。鱼C工作室中的‘atlf11’做了解答,改为re.compile(r'^(.*?)(0+)(.*)$')。仅仅加了一个'?'就完美解决了这个问题。
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():
mo = zeroPattern.search(filename)
# Skip file without '0' in the filename.
if mo == None:
continue
# Get the different parts of the filename.
beforePart = mo.group(1)
zeroPart = mo.group(2)
afterPart = mo.group(3)
# 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