看板 Python 關於我們 聯絡資訊
大家好, 最近想自己寫一個把特定目錄下所有DOC/DOCX的文件找出來然後 把路徑跟檔名寫入csv的小程式 但在寫入CSV的部份就遇到了問題~~ 想請問我那邊錯了? 以下是我的code import os import csv ##此段是測試有沒有抓到DOC/DOCX的 for file in os.listdir("E:\src"): if file.endswith(".doc") or file.endswith(".docx"): print(os.path.join("E:\src", file)) ##下面是要寫入CSV的部份 with open('FileSearchList.csv', 'w', newline = '', encoding = 'UTF-8') as csvfile: writer = csv.writer(csvfile) writer.writerow = (['os.path.join("E:\src", file']) 上面這段程式執行完後, 輸出的結果是_csv.writer object attribute 'writerow' is read-only 可以請版上的大家指導一下或是給我個修改的方向嗎? 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.227.140.47 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1600138181.A.A35.html
annheilong: 他的錯誤的意思是writerow這個成員是唯讀的 不能給值 09/15 11:25
moodoa3583: 把 writerow 後面的 = 刪掉 09/15 12:11
※ 編輯: davic (125.227.140.47 臺灣), 09/15/2020 12:17:41 ※ 編輯: davic (125.227.140.47 臺灣), 09/15/2020 12:18:20
moodoa3583: 可以寫成: 09/15 12:19
moodoa3583: with open('FileSearchList.csv', 'w', newline = '', 09/15 12:19
moodoa3583: encoding = 'UTF-8') as csvfile: 09/15 12:19
moodoa3583: writer = csv.writer(csvfile) 09/15 12:19
moodoa3583: for file in os.listdir(r"E:\src"): 09/15 12:19
moodoa3583: if file.endswith(".doc") or file.endswith( 09/15 12:19
moodoa3583: ".docx"): 09/15 12:19
moodoa3583: path = (os.path.join("E:\src", file)) 09/15 12:19
moodoa3583: writer.writerow([path]) 09/15 12:20
moodoa3583: print(path) 09/15 12:20
davic: 謝謝, 已解決了~~謝謝ANN 跟MOO 兩位的回覆 09/15 12:20
davic: 我是後來改成writer.writerows(list), 就OK了~~ 09/15 12:22