擅长:python、mysql、java
<p>如<a href="https://stackoverflow.com/questions/12994442/how-to-append-data-to-a-json-file">How to append data to a json file?</a>中所述,使用<code>a</code>模式不是一个好选择,我认为最好手动将获取的数据附加到<code>data.txt</code>中的可用列表中,如下所示:</p>
<pre><code>import json
import requests
def read_content(): # reads and returns the available list in data.txt
try:
with open('data.txt') as fd:
json_data = json.load(fd)
except:
json_data = [] # handle the first write, when the file does not exist
return json_data
url = 'https://api.github.com/users/sferik/followers?per_page=100&page=1'
repo = requests.get(url).json() # repo is a list
if repo:
available_content = read_content() # read available list in data.txt
available_content.extend(repo) # extend new list to the end of available list
with open('data.txt', 'w') as f: # write again, the mode is 'w'
json.dump(repo, f, sort_keys=True, indent=4)
</code></pre>