import json import requests url = " https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=1&num=40&sort=symbol&asc=1&node=hs_bjs&symbol=&_s_r_a=init" response = requests.get(url) response.encoding = "utf-8" data = response.text with open("C:\\Users\\huawei\\Desktop\\xcc.txt", "w", encoding="utf-8") as f: f.write(data) with open("C:\\Users\\huawei\\Desktop\\xcc.txt", "r", encoding="utf-8") as f: content = f.read() fr=open("C:\\Users\\huawei\\Desktop\\xcc.txt","r").read()#读文件 fw=open("C:\\Users\\huawei\\Desktop\\xinlangcaijing.csv","a") ls=json.loads(fr) data=[list(ls[0].keys())] for i in ls: data.append(list(i.values())) #将结果写入csv文件 for i in range(len(data)): fw.write(str(data[i][0])+","+str(data[i][2])+","+str(data[i][3])+","+str(data[i][4])+","+str(data[i][5])+","+str(data[i][6])+","+str(data[i][7])+","+str(data[i][8])+","+str(data[i][9])+","+str(data[i][10])+","+str(data[i][11])+","+str(data[i][12])+","+str(data[i][13])+"\n") fw.close()这个代码容易犯的错误,以及如何改正
时间: 2023-09-14 15:10:10 浏览: 116
TAIEX数据:可从https://www.twse.com.tw获取Json原始数据
这段代码容易出现以下问题:
1. 缺少空格或语法错误。第一行导入json模块时,需要在import和json之间添加空格。
2. 缺少模块导入。需要导入requests模块。
3. 网址错误。在url变量中,缺少https协议头。
4. 文件操作错误。在写入文件时,应该使用“w”模式打开文件,而在读取文件时,应该使用“r”模式打开文件。
5. JSON解析错误。需要使用json.loads()函数将JSON字符串转换为Python对象。
6. CSV文件写入错误。在写CSV文件时,应该使用逗号分隔每个字段,并使用换行符分隔每一行。
以下是修改后的代码:
```
import json
import requests
url = "https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=1&num=40&sort=symbol&asc=1&node=hs_bjs&symbol=&_s_r_a=init"
response = requests.get(url)
response.encoding = "utf-8"
data = response.text
with open("C:\\Users\\huawei\\Desktop\\xcc.txt", "w", encoding="utf-8") as f:
f.write(data)
with open("C:\\Users\\huawei\\Desktop\\xcc.txt", "r", encoding="utf-8") as f:
content = f.read()
fr = open("C:\\Users\\huawei\\Desktop\\xcc.txt", "r").read()
fw = open("C:\\Users\\huawei\\Desktop\\xinlangcaijing.csv", "w")
ls = json.loads(fr)
data = [list(ls[0].keys())]
for i in ls:
data.append(list(i.values()))
for i in range(len(data)):
fw.write(",".join([str(x) for x in data[i]]) + "\n")
fw.close()
```
阅读全文