[問題] 依LIST中的字串批次修改DOCX的檔名

作者: davic (無所事事的人)   2020-10-22 11:35:24
我做了一個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'
請問...我那裡做錯了?? 可以指導一下嗎?? 謝謝
作者: ddavid (謊言接線生)   2020-10-22 15:23:00
可能一:是不是有兩個目標檔名一樣?那第二個當然就失敗了可能二:我印象中Windows自己的rename不像linux的mv那樣同時可以同時搬動位置並更名,因此第二個參數不應該帶有路徑,但我不確定Python的os.rename是否受到此性質影響(不在Windows電腦前,目前沒法測)
作者: davic (無所事事的人)   2020-10-22 16:56:00
應該是找不到路徑..我把rename那段改成:for n, oldname in enumerate(oldnamelist):os.rename(os.path.join(path, oldname),os.path.join(path, newnamelist[n] ))
作者: asd01248967 (超級阿宗)   2020-10-23 03:53:00
os.path.spilt試過嗎?
作者: LP9527 (ㄊㄇ抽菸都去)   2020-10-24 02:12:00
我站內你我寫的版本了反正是 renamefilesF.docx 已經存在造成的

Links booklink

Contact Us: admin [ a t ] ucptt.com