[英]os.rename error: The System Cannot Find The Path Specified
我需要对许多子目录中的文件应用新的命名约定。 例如,一个子目录中的文件可能是:
它们都需要重命名才能遵循此约定:
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:[Error 3]系统找不到路径指定。
例:
C:\\ Users \\ Me / Google云端硬盘/目录/子目录/ ['Text文本的ABC字符串','ABC
我希望有人能看到我正在努力实现的目标,并为我指明正确的方向。
您的问题出在os.walk
,它没有按照您的使用方式做您想做的事:请参阅https://docs.python.org/2/library/os.html#os.walk
通过自上而下或自下而上移动目录树来生成文件名。 对于以目录顶部(包括顶部本身)为根的树中的每个目录,它都会生成一个三元组(目录路径,目录名,文件名)。
也许您打算执行以下操作:
for (dirpath, dirnames, filenames) in os.walk(path):
for filename in filenames:
oldName = os.path.join(dirpath, filename)
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.