我做了一個list, 要依LIST中的字串變更資料夾中的word檔名
ex:
folder中 N個docx
第一份word = test1.docx
List[0] = 測試
第一個word = test2.docx
List[1] = 測試2
要將folder 中第一份word 改名為 測試.docx, 第二份改為測試2.docx
continue...
code 如下:
import os
from docx import Document
##把命名的存在下列目錄的docnamelist.txt檔裡
NewNameListLocation = r"E:\Python"
list = []
##讀docnamelist裡的內容並顯示:
with open(r'E:\Python\docnamelist.txt', 'r', encoding = "utf-8") as
nametorenew:
for content in nametorenew:
content_line = content.replace('\n','')
## print(content_line)
## print(content)
list.append(content_line)
##單純檢查是否有寫入list中
for items in list:
print(items)
##下段是做更名的動作
##把要更名的DOC存在此FOLDER中
Doctargetpath = r"E:\Python\renamefiles"
oldnames = os.listdir(Doctargetpath)
i=0
a=0
for a in range(len(oldnames)):
print(oldnames[a])
path_name = Doctargetpath + "\\" + oldnames[a]
try:
document = Document(path_name)
except:
print("Error!!")
##將第N個DOC檔名更名為LIST中的第N個字串
else:
newname = Doctargetpath + str(items[i]) + '.docx'
##try:
os.rename(path_name, newname)
i=i+1
但~~~~
error msg:
Traceback (most recent call last):
File
"C:/Programs/Python/Python38-32/renametest.py",
line 33, in <module>
os.rename(path_name, newname)
FileExistsError: [WinError 183] 當檔案已存在時,無法建立該檔案。:
'E:\\Python\\renamefiles\\renamefilesF - 複製 (10) - 複製.docx' ->
'E:\\Python\\renamefilesF.docx'
請問...我那裡做錯了?? 可以指導一下嗎?? 謝謝