I would suggest a couple of simplifications. If all you are doing with re
is stripping off the trailing newlines there is a better way for example. After that, I think you really want to look at a list comprehension to build your final user data.
Check out:
import requests
## ---------------------------
## Read usernames out of a text file.
## ---------------------------
with open("u.txt", "r") as file_in:
post_data = {
"usernames": [username.strip() for username in file_in][:100],
"excludeBannedUsers": True
}
## ---------------------------
post_url = "https://users.roblox.com/v1/usernames/users"
api_response = requests.post(post_url, post_data)
if not api_response.ok():
print("something went wrong")
exit()
## ---------------------------
## Build a list of dictionaries based on the api data
## ---------------------------
user_data = [
{user["id"]: user["name"]}
for user
in api_response.json()["data"]
]
## ---------------------------
## ---------------------------
## Print the results
## ---------------------------
import json
for user in user_data:
print(json.dumps(user, indent=4))
## ---------------------------
Addendum:
To work through the list in batches of 100 ignoring errors you might do:
import requests
post_url = "https://users.roblox.com/v1/usernames/users"
## ---------------------------
## Read usernames out of a text file.
## ---------------------------
with open("u.txt", "r") as file_in:
all_username = [username.strip() for username in file_in]
## ---------------------------
## ---------------------------
## process the usernames in batches of n=100
## ---------------------------
batch_size = 100
user_data = []
for i in range(0, len(all_username), batch_size):
post_data = {
"usernames": all_username[i: i + batch_size],
"excludeBannedUsers": True
}
try:
api_response = requests.post(post_url, post_data)
except requests.HTTPError as e:
print(e)
continue
## ---------------------------
## add users to list
## ---------------------------
user_data.extend([
{user["id"]: user["name"]}
for user
in api_response.json()["data"]
])
## ---------------------------
## ---------------------------
## Print the results
## ---------------------------
import json
for user in user_data:
print(json.dumps(user, indent=4))
## ---------------------------