You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python代码报错AttributeError: 'str'对象无'read'属性,求修复方法

AttributeError when parsing API response with json.load() in Python

I wrote a Python script to iterate through BIN numbers, call an API to get the corresponding country code, and write the results to a file. Here's my code:

import requests as req
import json
Bin = int(300000)
BinMax = int(600000)
File = open("C:/Users/admin/Desktop/PS Now Generaetors/Bins.txt", 'a')
while bin != BinMax:
    json1 = req.get("https://lookup.binlist.net/" + str(Bin))
    json2 = json1.text
    jsonout = json.load(json2)
    country = jsonout["country"]
    cc = country["alpha2"]
    if cc == "US" or "AT" or "BE" or "CA" or "FR" or "De" or "IE" or "JP" or "LU" or "NL" or "CH" or "GB" or "ES" or "IT" or "PT" or "NO" or "DK" or "FI" or "SE" or "PH":
        print (bin, "writed")
        File.write("\n" + str(Bin) + ";" + cc)
    bin =+ 1

When I run it, I get this error:

Traceback (most recent call last):
  File "C:\Users\admin\Desktop\PS Now Generaetors\Bin generator.py", line 10, in <module>
    jsonout = json.load(json2)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1008.0_x64__qbz5n2kfra8p0\lib\json\__init__.py", line 293, in load
    return loads(fp.read(), 
AttributeError: 'str' object has no attribute 'read'

How can I fix this error?


Fixing the Core Error

Let's start with the immediate issue: you're mixing up json.load() and json.loads():

  • json.load() is designed to read from file-like objects (things with a .read() method, like an open file)
  • json.loads() parses raw JSON strings directly (which is exactly what json1.text returns)

So replace this line:

jsonout = json.load(json2)

With either:

jsonout = json.loads(json2)

Or even better, use the requests library's built-in .json() method—it parses the response straight into a Python dictionary, saving you a step:

jsonout = json1.json()

Fixing Other Hidden Bugs

Your script has a few other issues that will cause problems even after fixing the AttributeError:

  1. Case-sensitive variable names
    You initialize Bin = 300000 but use bin in your loop and increment. Python is case-sensitive, so bin is an undefined variable here. Stick to consistent naming (I'll use current_bin to avoid conflicting with Python's built-in bin() function).

  2. Broken increment syntax
    bin =+ 1 sets the variable to +1 every time—you want bin += 1 to increment by 1 each loop.

  3. Invalid conditional check
    The line if cc == "US" or "AT" or ... doesn't work as intended. Non-empty strings are truthy in Python, so this condition will always evaluate to True. Instead, check if cc is in a set of allowed codes:

    allowed_cc = {"US", "AT", "BE", "CA", "FR", "DE", "IE", "JP", "LU", "NL", "CH", "GB", "ES", "IT", "PT", "NO", "DK", "FI", "SE", "PH"}
    if cc in allowed_cc:
    

    Note: I corrected "De" to "DE" since country codes are standardized to uppercase.

  4. Unsafe API handling
    Not all BIN numbers will return a valid response—some might fail (e.g., 404 error) or lack a country field. Add error handling to avoid crashes.

  5. Unclosed file
    You open the file but never close it. Use a with statement to handle file management automatically—it will close the file even if an error occurs.

Full Fixed Code

Here's the revised script with all fixes applied:

import requests as req

allowed_cc = {"US", "AT", "BE", "CA", "FR", "DE", "IE", "JP", "LU", "NL", "CH", "GB", "ES", "IT", "PT", "NO", "DK", "FI", "SE", "PH"}
current_bin = 300000
bin_max = 600000

# Use with statement to handle file safely
with open("C:/Users/admin/Desktop/PS Now Generaetors/Bins.txt", 'a') as file:
    while current_bin < bin_max:
        try:
            response = req.get(f"https://lookup.binlist.net/{current_bin}")
            # Check if request succeeded
            if not response.ok:
                print(f"Failed to fetch BIN {current_bin}: {response.status_code}")
                current_bin += 1
                continue
            
            data = response.json()
            # Safely get country and alpha2 code
            country = data.get("country")
            if not country:
                print(f"No country data for BIN {current_bin}")
                current_bin += 1
                continue
            
            cc = country.get("alpha2")
            if cc and cc in allowed_cc:
                print(f"{current_bin} written")
                file.write(f"\n{current_bin};{cc}")
        except Exception as e:
            print(f"Error processing BIN {current_bin}: {str(e)}")
        
        current_bin += 1

Key Improvements

  • Eliminates the original AttributeError by using response.json()
  • Case-consistent variable names and correct increment syntax
  • Robust conditional check for allowed country codes
  • Error handling for failed requests and missing data
  • Automatic file management with with statement

内容的提问来源于stack exchange,提问作者farkon00

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 21:22:49