我需要对许多子目录中的文件应用新的命名约定。例如,一个子目录中的文件可能是:
他们需要全部重命名才能遵循这个惯例:
import os, re
regex = re.compile('\s\([a-zA-Z]+\)')
path = os.path.expanduser('~/Google Drive/Directory/Subdirectory/')
for files in os.walk(path):
for name in files:
strname = str(name)
oldName = os.path.join(path,strname)
if(regex.search(strname)):
# identifying the token that needs shuffling
token = regex.findall(oldName)
# remove the token
removed = (regex.split(oldName)[0] + ' ' +
regex.split(oldName)[1].strip())
print removed # this is where everything goes wrong
# remove the file extension
split = removed.split('.')
# insert the token at the end of the filename
reformatted = split[0] + token[0]
# reinsert the file extension
for i in range(1,len(split)):
reformatted += '.' + split[i]
os.rename(oldName,reformatted)
它最终试图通过从目录中的文件列表中提取子字符串来重命名文件,但包括与列表相关的字符,如" ["和"'",导致WindowsError:[错误3]系统找不到指定的路径。
示例:
C:\ Users \ Me / Google Drive / Directory / Subdirectory / [' Text.txt的ABC字符串',' ABC
我希望有人可以看到我想要完成的事情,并指出我正确的方向。
答案 0 :(得分:0)
您的问题出在os.walk
上,而您使用它的方式并不理想:请参阅https://docs.python.org/2/library/os.html#os.walk
通过遍历树来生成目录树中的文件名 自上而下或自下而上。对于以树为根的树中的每个目录 目录顶部(包括顶部本身),它产生一个3元组(dirpath, dirnames,filenames)。
也许你的意思是这样做:
for (dirpath, dirnames, filenames) in os.walk(path):
for filename in filenames:
oldName = os.path.join(dirpath, filename)
...