0

我正在使用 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 部分对齐

4

1 回答 1

0

urllib.request.urlopen返回一个类似文件的对象。

这些对象公开了一个读取方法,但不应允许您写入。

我喜欢把它想象成,在使用urllib它时,就像在浏览器中输入资源一样请求文件。你不能给它写信。你请求它,它就会送达给你。

如果要打开文件进行写入,可以使用该open方法

with open('E:/Programming/Calculator.html', 'w+') as f:
   f.write('something')

上面的示例使用with语句,它基本上是在代码退出 with 块时手动关闭文件的快捷方式。

它类似于

f = open('E:/Programming/Calculator.html', 'w+')
f.write('something')
f.close()

@Lattyware 发布了一个很棒的教程,更多可以在网上找到。鼓舞人心的概述了它的用途。

看来您可能会混淆urlopen命令open

于 2013-07-31T15:13:28.320 回答