作者davic (無所事事的人)
看板Python
標題[問題] 新手請教 寫入CSV檔的問題[己解決]
時間Tue Sep 15 10:49:39 2020
大家好,
最近想自己寫一個把特定目錄下所有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://webptt.com/m.aspx?n=bbs/Python/M.1600138181.A.A35.html
1F:推 annheilong: 他的錯誤的意思是writerow這個成員是唯讀的 不能給值 09/15 11:25
2F:推 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
3F:→ moodoa3583: 可以寫成: 09/15 12:19
4F:→ moodoa3583: with open('FileSearchList.csv', 'w', newline = '', 09/15 12:19
5F:→ moodoa3583: encoding = 'UTF-8') as csvfile: 09/15 12:19
6F:→ moodoa3583: writer = csv.writer(csvfile) 09/15 12:19
7F:→ moodoa3583: for file in os.listdir(r"E:\src"): 09/15 12:19
8F:→ moodoa3583: if file.endswith(".doc") or file.endswith( 09/15 12:19
9F:→ moodoa3583: ".docx"): 09/15 12:19
10F:→ moodoa3583: path = (os.path.join("E:\src", file)) 09/15 12:19
11F:→ moodoa3583: writer.writerow([path]) 09/15 12:20
12F:→ moodoa3583: print(path) 09/15 12:20
13F:→ davic: 謝謝, 已解決了~~謝謝ANN 跟MOO 兩位的回覆 09/15 12:20
14F:→ davic: 我是後來改成writer.writerows(list), 就OK了~~ 09/15 12:22