在下次运行时执行的python文件中写入

gop*_*410 1 python file

我有以下代码:

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
Run Code Online (Sandbox Code Playgroud)

现在,当我执行代码时,上一次运行的输出进入文件data.txt

例如,现在我在url中有example.com,我运行代码然后我将url更改为stackoverflow.com.现在,当我再次运行它并检查data.txt时,我在data.txt文件中输出了example.com.下次我使用不同的url运行时,我会在文件中输出stackoverflow.com.有人可以帮我解决这个问题吗?我检查了代码中每个阶段的输出.如果我直接给出输出而不是写入文件,它完美地工作.

Mar*_*ers 5

您可能想要使用f.close()而不是f.closed.后者不会关闭文件.它返回一个布尔值,告诉您文件是否已关闭.

我还建议您使用with语句而不是手动关闭文件.

with open('data.txt', 'w') as f:
    # etc...
Run Code Online (Sandbox Code Playgroud)

  • @ gopi1410``f.close()``是一个关闭文件的函数.``f.closed``是一个告诉你文件是否关闭的属性.您可能应该更仔细地阅读文档 - 在Python中非常罕见,有两种方法可以做一件事(这是一个特定的设计目标,没有). (3认同)