Python基础-从API请求数据并写入文件 [英] Python basics - request data from API and write to a file

查看:75
本文介绍了Python基础-从API请求数据并写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用请求"包并从Github检索信息,如请求"文档页面上所述:

I am trying to use "requests" package and retrieve info from Github, like the Requests doc page explains:

import requests
r = requests.get('https://api.github.com/events')

这:

with open(filename, 'wb') as fd:
    for chunk in r.iter_content(chunk_size):
        fd.write(chunk)

我不得不说我不理解第二个代码块.

I have to say I don't understand the second code block.

  • 文件名-如果创建文件,我应以什么形式提供文件的路径?如果没有,它将保存在哪里?
  • 'wb'-此变量是什么?(第二个参数不是'mode'吗?)
  • 以下两行可能会遍历通过请求检索的数据并写入文件

Python文档的解释也无济于事.

Python docs explanation also not helping much.

我正在尝试做的事情:

  • 使用请求连接到API(Github和更高版本的Facebook GraphAPI)
  • 将数据检索到变量
  • 将此内容写入文件(后来,随着我对Python的熟悉,它写入我的本地MySQL数据库中)

推荐答案

文件名

使用 open 时,该路径是相对于当前目录的.因此,如果您说 open('file.txt','w'),它将在您的python脚本所在的任何文件夹中创建一个名为 file.txt 的新文件.也可以指定绝对路径,例如linux中的/home/user/file.txt .如果已经存在名称为'file.txt'的文件,则内容将被完全覆盖.

Filename

When using open the path is relative to your current directory. So if you said open('file.txt','w') it would create a new file named file.txt in whatever folder your python script is in. You can also specify an absolute path, for example /home/user/file.txt in linux. If a file by the name 'file.txt' already exists, the contents will be completely overwritten.

'wb'选项确实是该模式.'w'表示写,而'b'表示字节.要从文件写入(而不是读取)时,请使用'w',对于二进制文件(而不是文本文件)使用'b'.在这种情况下,使用'b'实际上有点奇怪,因为您要编写的内容是文本文件.指定'w'在这里同样适用.在打开文档中阅读更多有关模式.

The 'wb' option is indeed the mode. The 'w' means write and the 'b' means bytes. You use 'w' when you want to write (rather than read) froma file, and you use 'b' for binary files (rather than text files). It is actually a little odd to use 'b' in this case, as the content you are writing is a text file. Specifying 'w' would work just as well here. Read more on the modes in the docs for open.

这部分使用的是 requests 中的 iter_content 方法,该方法旨在用于可能不需要一次全部存储的大型文件.在这种情况下,这是不必要的,因为所讨论的页面只有89 KB.有关更多信息,请参见请求库文档.

This part is using the iter_content method from requests, which is intended for use with large files that you may not want in memory all at once. This is unnecessary in this case, since the page in question is only 89 KB. See the requests library docs for more info.

您正在查看的示例旨在处理最一般的情况,在这种情况下,远程文件可能是二进制文件,太大而无法保存在内存中.但是,如果您只访问包含文本的小型网页,我们可以使您的代码更具可读性和易于理解:

The example you are looking at is meant to handle the most general case, in which the remote file might be binary and too big to be in memory. However, we can make your code more readable and easy to understand if you are only accessing small webpages containing text:

import requests
r = requests.get('https://api.github.com/events')

with open('events.txt','w') as fd:
    fd.write(r.text)

这篇关于Python基础-从API请求数据并写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆