我正在使用 python 3,我能够从我的 html 文档中读取代码,但我无法写入它。我该怎么办。我会告诉你我的意思:
import urllib.request
locator=urllib.request.urlopen("file:///E:/Programming/Calculator.html", "r")
transfer=locator.read()
print("\n\n",transfer, "\n")
locator.close()
locator=urllib.request.urlopen("file:///E:/Programming/Calculator.html","w+")
locator.write("<p> Hello this site has been slightly changed</p>")
locator.close()
locator=urllib.request.urlopen("file:///E:/Programming/Calculator.html","r")
new=locator.read()
print(new)
locator.close()
所以我要读它,但我不能写它或改变它的任何代码。为什么是这样?
此外,我尝试使用与上面完全相同的代码从实际的 url 网站读取数据,但替换了 url 并删除了 write 函数。口译员遇到了一个错误,我无法从网站上阅读。我如何也可以从网站上阅读?
注意:我只是在学习,我实际上不会做任何违法的事情我只是想对这种东西变得更加了解
另外,如果我将 write 更改为 append() 它仍然会产生错误
import urllib.request
locator=urllib.request.urlopen("file:///E:/Programming/Calculator.html", "r")
transfer=locator.read()
print("\n\n",transfer, "\n")
locator.close()
locator=urllib.request.urlopen("file:///E:/Programming/Calculator.html", "w+")
with open("file:///E:/Programming/Calculator.html") as f:
f.write('something')
locator.close()
上面是另一个成员 ut 建议的一段代码,而不是写到 url 并显示错误:
Traceback (most recent call last):
File "C:\Users\KENNY\Desktop\Python\practice.py", line 10, in <module>
with open("file:///E:/Programming/Calculator.html") as f:
OSError:[Errno 22] 无效参数:'file:///E:/Programming/Calculator.html'
忽略间距,它只是我粘贴它的方式。所有代码都应与 f.write 函数所在的 with open 部分对齐