2016-04-03 58 views
0

嗨我想要創建文件的名稱file1.txt,file2.txt等...我得到它的極限錯誤。我需要在代碼中做些什麼才能使其工作?如何使用for循環寫入多個文件?

from bs4 import BeautifulSoup 

f = open('reut2-000.sgm', 'r') 
data= f.read() 
soup = BeautifulSoup(data, "html.parser") 

contents = soup.findAll('body') 
for i, content in contents: 
    file = open("file%i.txt" %i,'w') 
    file.write(content.text) 
    file.close() 

我得到了ValueError: need more than 1 value to unpack錯誤。當我給環路里面我我得到錯誤IOError: [Errno 24] Too many open files: 'file508.txt'

+3

什麼是極限誤差?那是不是'['錯字?這可能是問題 – Jasper

+1

發佈特定的錯誤消息。操作系統通常會對打開的文件句柄數量有限制。這是可能的(但我不希望)你的循環中的'del file'會有幫助。 –

+0

我期望'SyntaxError'在這裏 - 你是否試圖每次寫入每個結果的身體到一個新的文件? –

回答

0

ValueError: need more than 1 value to unpack

contents你的情況將包含bs4.Tag實例的列表。如果你想「索引」他們 - 使用enumerate()

for i, content in enumerate(contents): 
    file = open("file%i.txt" % i,'w') 
    file.write(content.text) 
    file.close()