【问题标题】:Does .write(string) replace all file with the new string or just append it? [duplicate].write(string) 是用新字符串替换所有文件还是只是附加它? [复制]
【发布时间】:2018-03-09 00:32:48
【问题描述】:

我用来学习的编码:

import requests


r = requests.get("http://google.com")

f = open("./page.html", "w+")
f.write(r.text)

因此,如果我理解正确,这将创建一个 .html 文件并在其中写入我请求 (r) 的 google.com html 代码。

如果我现在运行:

import requests

params = {"q": "pizza"}
r = requests.get("http://google.com/search", params=params)

f = open("./page.html", "w+")
f.write(r.text)

f.write(r.text) 是否会重写 'r' 变量上的所有内容,就像它是一个空白文件一样,或者它只会用我添加到 'r' 中的新内容来编辑文件?不知道怎么问。谢谢

编辑:没关系我是菜鸟!如果我想追加使用f = open("./page.html", "a"),如果我想覆盖使用'w'

【问题讨论】:

标签: python html file python-requests


【解决方案1】:

这一切都取决于您如何打开文件

模式表示,文件将如何打开 "r" for 阅读,“w”代表写作,“a”代表追加。

f = open("./page.html", "r")
f = open("./page.html", "w")
f = open("./page.html", "a")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    • 2016-10-11
    • 1970-01-01
    相关资源
    最近更新 更多