Python3.7循环写入JSON文件时遇PermissionError: [Errno13]权限拒绝求助
解决PermissionError及代码优化方案
问题根源分析
你的代码存在两个核心问题,会直接或间接触发PermissionError:
- 循环内频繁操作文件:每次循环都打开、写入、关闭文件,高频的文件IO操作可能触发系统权限限制,或导致文件句柄未及时释放。
- JSON格式无效:每次追加写入整个
json_arr,最终文件会包含多个独立的JSON数组,属于非法JSON格式,后续操作文件时的异常可能间接引发权限问题。
解决方案
1. 先收集所有数据,一次性写入文件(推荐)
这种方式既避免频繁文件操作,又能生成合法的JSON数组:
import pandas as pd import requests import json df_loc_missed = pd.DataFrame(columns=['location_id', 'city', 'country']) json_arr = [] headers = {'Accept': 'application/json'} # 先循环收集所有API返回的有效数据 for row in missed_loc_id.itertuples(index=True, name='Pandas'): loc_id = row.location_id url = f"https://europa.eu/v1/locations/{loc_id}" response = requests.get(url, auth=('hghgh', 'ghghgh$'), headers=headers) # 增加状态码检查,过滤无效响应 if response.status_code == 200: json_arr.append(response.json()) # 一次性写入完整的JSON数组 with open("missed_location.json", "w", encoding='utf-8') as myfile: json.dump(json_arr, myfile, ensure_ascii=False, indent=4) # with语句会自动关闭文件,无需手动调用myfile.close()
2. 追加写入JSON Lines格式(适用于大数据量场景)
如果数据量极大无法全部存入内存,可以采用JSON Lines格式,每行存储一个独立的JSON对象:
import pandas as pd import requests import json df_loc_missed = pd.DataFrame(columns=['location_id', 'city', 'country']) headers = {'Accept': 'application/json'} # 打开文件后持续写入 with open("missed_location.json", "a", encoding='utf-8') as myfile: for row in missed_loc_id.itertuples(index=True, name='Pandas'): loc_id = row.location_id url = f"https://europa.eu/v1/locations/{loc_id}" response = requests.get(url, auth=('hghgh', 'ghghgh$'), headers=headers) if response.status_code == 200: json.dump(response.json(), myfile, ensure_ascii=False) myfile.write('\n') # 用换行分隔每个JSON对象
额外注意事项
- 检查
missed_location.json是否被其他程序占用(比如记事本、代码编辑器),关闭这些程序后再运行代码。 - 确保当前用户对文件所在目录有写入权限,若权限不足,可更换到用户个人目录等有权限的路径保存文件。
- 不要硬编码认证凭证,建议使用环境变量或配置文件存储,避免敏感信息泄露。
内容的提问来源于stack exchange,提问作者rshar
相关产品推荐
相关产品推荐

