2016-04-03 56 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()