gpt4 book ai didi

python - 读取 Python 请求到文件

转载 作者:行者123 更新时间:2023-12-01 04:33:03 24 4
gpt4 key购买 nike

我正在使用请求库发出 RESTapi 请求。我可以成功执行获取并从服务器接收正确的响应。我正在尝试将 GET 的响应保存到文件中,以便我可以操作数据。

我没有收到错误,但没有任何内容写入文件:

def download_file(url, cafile, user1, pass1, local_filename):
# NOTE the stream=True parameter
r = requests.get(url,
stream=True,
auth=(user1, pass1),
verify=cafile,
headers={'content-type':'application/xml'}
)
lines = r.iter_lines()
first_line = next(lines)
for line in lines:
with open(local_filename, 'w')as g:
g.write((line)+ '/')
return (local_filename)

最佳答案

通过在循环中打开文件来保持覆盖,在循环外打开一次:

  with open(local_filename, 'w')cas g:
for line in lines:

'w' 打开一个文件进行写入,并将截断该文件,这样您在文件中只能得到一行数据。
您可以在循环中使用 a 打开文件进行附加,但在循环外打开文件更有意义。

我还会打印 first_line 以及循环中的每一行,以准确验证返回的内容。

关于python - 读取 Python 请求到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32104220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com