打开文件进行追加
Opening a file for appending
编辑:我似乎以临时方式修复了它。我确实认为这是一个实用的解决方案,但这是一个不可接受的答案。我在写入之前添加的只是一个 fp.read() 语句。谁能解释为什么这会避免 Errno 0?这就是没有 fp.read() 行的情况。
我一直在尝试制作一个脚本,每天将一些 html 代码附加到我的笔记文件中。不过我更新文件时遇到了问题。我已经尝试了所有 open()
标签(r
、w
、a
、r+
等...)。
代码:
从 bs4 导入 BeautifulSoup
bs=BeautifulSoup
import datetime
with open("crossfireNewNotes.html",'a+') as fp:
soup= bs(fp,"lxml")
print "8 " + str(soup)
print "9 " + str(soup.html)
today=str(datetime.date.today())
print "11 " + str(soup)
if soup.select("body#" + today) ==[]:
new_body=soup.new_tag("body",id=today)
new_p=soup.new_tag("p")
new_olink=soup.new_tag("a",link=today)
new_ilink=soup.new_tag("a",href=today)
soup.html.append(new_body)
soup.html.select("body#" + today)[0].append(new_olink)
soup.html.select("body#" + today)[0].select("a[link=" + today + "]").append(new_p)
soup.body.insert_before(new_ilink)
print "25 " + str(soup)
fp.read()
fp.write(str(soup))
fp.close()
之前,文件对象是 NoneType,给我带来了其他问题。现在它似乎可以正常打开,但我在 cmd 中有以下输出:
Line 8: <html></html>
Line 11: <html></html>
Line 25: <html><a href="2018-08-18"></a><body id="2018-08-18"><a link="2018-08-18"></a></body></html>
Traceback (most recent call last):
File "noter.py", line 29, in (module)
fp.write(str(soup))
IOError: [Errno 0] Error
或者,如果有人有任何更好的方法,我会向他们开放。
您遇到的问题在于以 append
模式打开文件处理程序 fp
和通过 soup.html.append
和 soup.html.select
方法移动指针。一旦您想写入文件,您的指针就不再位于文件末尾。如果你 read()
文件,那么指针又在末尾,因此你可以再次写入。更好的方法是 fp.seek(0,2)
找到文件的结尾。
更好的是,您可以先将 html 文件的内容加载到 BeautifulSoup,进行更改,然后从 soup 对象写入文件,从而使用两个单独的文件 IOs.
编辑:我似乎以临时方式修复了它。我确实认为这是一个实用的解决方案,但这是一个不可接受的答案。我在写入之前添加的只是一个 fp.read() 语句。谁能解释为什么这会避免 Errno 0?这就是没有 fp.read() 行的情况。
我一直在尝试制作一个脚本,每天将一些 html 代码附加到我的笔记文件中。不过我更新文件时遇到了问题。我已经尝试了所有 open()
标签(r
、w
、a
、r+
等...)。
代码:
从 bs4 导入 BeautifulSoup bs=BeautifulSoup
import datetime
with open("crossfireNewNotes.html",'a+') as fp:
soup= bs(fp,"lxml")
print "8 " + str(soup)
print "9 " + str(soup.html)
today=str(datetime.date.today())
print "11 " + str(soup)
if soup.select("body#" + today) ==[]:
new_body=soup.new_tag("body",id=today)
new_p=soup.new_tag("p")
new_olink=soup.new_tag("a",link=today)
new_ilink=soup.new_tag("a",href=today)
soup.html.append(new_body)
soup.html.select("body#" + today)[0].append(new_olink)
soup.html.select("body#" + today)[0].select("a[link=" + today + "]").append(new_p)
soup.body.insert_before(new_ilink)
print "25 " + str(soup)
fp.read()
fp.write(str(soup))
fp.close()
之前,文件对象是 NoneType,给我带来了其他问题。现在它似乎可以正常打开,但我在 cmd 中有以下输出:
Line 8: <html></html>
Line 11: <html></html>
Line 25: <html><a href="2018-08-18"></a><body id="2018-08-18"><a link="2018-08-18"></a></body></html>
Traceback (most recent call last):
File "noter.py", line 29, in (module)
fp.write(str(soup))
IOError: [Errno 0] Error
或者,如果有人有任何更好的方法,我会向他们开放。
您遇到的问题在于以 append
模式打开文件处理程序 fp
和通过 soup.html.append
和 soup.html.select
方法移动指针。一旦您想写入文件,您的指针就不再位于文件末尾。如果你 read()
文件,那么指针又在末尾,因此你可以再次写入。更好的方法是 fp.seek(0,2)
找到文件的结尾。
更好的是,您可以先将 html 文件的内容加载到 BeautifulSoup,进行更改,然后从 soup 对象写入文件,从而使用两个单独的文件 IOs.