[問題] 以LIST中的內容產生WORD文件

看板Python作者 (無所事事的人)時間3年前 (2020/10/22 11:35), 3年前編輯推噓3(309)
留言12則, 4人參與, 3年前最新討論串1/1
我做了一個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' 請問...我那裡做錯了?? 可以指導一下嗎?? 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.227.140.47 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1603337726.A.A0A.html ※ 編輯: davic (125.227.140.47 臺灣), 10/22/2020 11:40:34 ※ 編輯: davic (125.227.140.47 臺灣), 10/22/2020 13:43:41

10/22 15:23, 3年前 , 1F
可能一:是不是有兩個目標檔名一樣?那第二個當然就失敗了
10/22 15:23, 1F

10/22 15:23, 3年前 , 2F
可能二:我印象中Windows自己的rename不像linux的mv那樣同
10/22 15:23, 2F

10/22 15:24, 3年前 , 3F
時可以同時搬動位置並更名,因此第二個參數不應該帶有路徑
10/22 15:24, 3F

10/22 15:24, 3年前 , 4F
,但我不確定Python的os.rename是否受到此性質影響(不在
10/22 15:24, 4F

10/22 15:24, 3年前 , 5F
Windows電腦前,目前沒法測)
10/22 15:24, 5F

10/22 16:56, 3年前 , 6F
應該是找不到路徑..我把rename那段改成:
10/22 16:56, 6F

10/22 16:56, 3年前 , 7F
for n, oldname in enumerate(oldnamelist):
10/22 16:56, 7F

10/22 16:57, 3年前 , 8F
os.rename(os.path.join(path, oldname),
10/22 16:57, 8F

10/22 16:57, 3年前 , 9F
os.path.join(path, newnamelist[n] ))
10/22 16:57, 9F
※ 編輯: davic (125.227.140.47 臺灣), 10/22/2020 16:58:25

10/23 03:53, 3年前 , 10F
os.path.spilt試過嗎?
10/23 03:53, 10F

10/24 02:12, 3年前 , 11F
我站內你我寫的版本了
10/24 02:12, 11F

10/24 02:13, 3年前 , 12F
反正是 renamefilesF.docx 已經存在造成的
10/24 02:13, 12F
文章代碼(AID): #1VaFt-eA (Python)