[問題] os.listdir後open text問題

看板Python作者 (hc)時間9年前 (2016/04/25 14:37), 9年前編輯推噓2(202)
留言4則, 4人參與, 最新討論串1/1
python 新手想請問openfile的問題 一段code如下 # -*- coding: UTF-8 -*- import os, sys path= "/home/puoud/documents" dirs = os.listdir(path) for file in dirs: print file 若我想將documents內的每一個.txt都read 請問在下一個段落open(file,'r').open() 出錯在哪裡? 出錯 IOError: [Errno 2] No such file or directory: xxxx.txt 請問怎麼打比較正確? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.240.33.180 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1461566266.A.5EF.html

04/25 14:55, , 1F
open的路徑是path+file吧
04/25 14:55, 1F
感謝!

04/25 17:20, , 2F
最簡單的解法 open(path+'/'+file,'r').
04/25 17:20, 2F
解決了,感謝! ※ 編輯: proud (180.204.20.230), 04/25/2016 22:07:37

04/25 22:38, , 3F
可以用os.path.join合併
04/25 22:38, 3F

04/30 12:22, , 4F
沒人提glob嗎?
04/30 12:22, 4F
文章代碼(AID): #1N7RiwNl (Python)
文章代碼(AID): #1N7RiwNl (Python)