Python代码报错AttributeError: 'str'对象无'read'属性,求修复方法
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 whatjson1.textreturns)
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:
Case-sensitive variable names
You initializeBin = 300000but usebinin your loop and increment. Python is case-sensitive, sobinis an undefined variable here. Stick to consistent naming (I'll usecurrent_binto avoid conflicting with Python's built-inbin()function).Broken increment syntax
bin =+ 1sets the variable to+1every time—you wantbin += 1to increment by 1 each loop.Invalid conditional check
The lineif cc == "US" or "AT" or ...doesn't work as intended. Non-empty strings are truthy in Python, so this condition will always evaluate toTrue. Instead, check ifccis 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.
Unsafe API handling
Not all BIN numbers will return a valid response—some might fail (e.g., 404 error) or lack acountryfield. Add error handling to avoid crashes.Unclosed file
You open the file but never close it. Use awithstatement 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
withstatement
内容的提问来源于stack exchange,提问作者farkon00

