作者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/cn.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