我有以下代码:
f=open('data.txt', 'w')
conn = urllib2.urlopen('http://example.com')
page_html = conn.read()
data=BeautifulSoup(page_html)
count=0
out=""
for val in data.findAll('td'):
count=count+1
if(count%2==0 and val.contents):
out=out+val.contents[0].strip(' \n\t')+"\n"
if(count>=18):
f.write(out+"\n")
break
f.closed
现在当我执行代码时,上一次运行的输出进入文件 data.txt
例如,现在我的 url 中有 example.com,我运行代码然后将 url 更改为 stackoverflow.com。现在,当我再次运行它并检查 data.txt 时,我在 data.txt 文件中有 example.com 的输出。下次我使用不同的 url 运行时,我会在文件中得到 stackoverflow.com 的输出。有人可以帮我解决这个问题吗?我检查了代码中每个阶段的输出。如果我直接给出输出而不是写入文件,它会完美地工作。
最佳答案
您可能想使用 f.close()
而不是 f.closed
。后者不会关闭文件。它返回一个 bool 值,告诉您文件是否已关闭。
我还建议您使用 with
statement而不是手动关闭文件。
with open('data.txt', 'w') as f:
# etc...
关于python - 在下次运行时执行的 python 中写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10353215/