[英]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.