[問題] file讀取問題

看板Python作者時間17年前 (2008/07/21 00:27), 編輯推噓1(106)
留言7則, 3人參與, 最新討論串1/2 (看更多)
class random_pick: def __init__(self,file_name): self.r_content = open(file_name).readlines() def random_pick(self,num): w_content = random.sample(self.r_content,num) def writeTofile(self): pass def mergeFile(self,*files): self.data = [] for file_name in files: self.data = open(file_name).readlines() files = ['0.txt','t2.txt'] x.mergeFile(files) 在mergeFile這個function會出錯, 誤訊息是TypeError: coercing to Unicode: need string or buffer, list found 改了很多次還是不曉得為啥會錯= =" 這個function主要是拿來把很多檔案合成一個,方便處理 不過現在寫的有些問題,希望各位能幫忙看看@@" 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.115.223.231

07/21 00:42, , 1F
def mergeFile(self,*files): <-- files 前面不用加*
07/21 00:42, 1F

07/21 00:44, , 2F
另外: open檔案後 最好加上close 可以避免重複開啟的問題
07/21 00:44, 2F

07/21 00:48, , 3F
以及開啟太多檔案的問題
07/21 00:48, 3F

07/21 01:10, , 4F
謝謝你的回答,不過又遇到另一個問題
07/21 01:10, 4F

07/21 01:12, , 5F
print self.data會說class中沒有這個attribute 囧
07/21 01:12, 5F

07/21 08:46, , 6F
要先在__init__()裡面初始化data這個attribute才能在其他
07/21 08:46, 6F

07/21 08:46, , 7F
method裏面使用他喔
07/21 08:46, 7F
文章代碼(AID): #18WsTpYF (Python)
討論串 (同標題文章)
文章代碼(AID): #18WsTpYF (Python)