Have some issues with python [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 days ago.
Improve this question
im using this phone number validator but since they changed the api url its not working anymore..
Here is the original code:
phone_number = open(input(f'\n{cy}Enter Phone Number List{res} : '),'r').read().splitlines()
access_key = input(f'\n{yl}Enter Your Access Key {red}[ Numverify ]{res} : ')
print('------------------------------------------------------------------')
for i in phone_number :
url = 'http://apilayer.net/api/validate?access_key=' + access_key + '&number=' + str(i)
response = requests.get(url)
answer = response.json()
if answer["carrier"] :
print(f'{gr}{answer["number"]}{res}{yl} => {cy}{answer["carrier"]}{res}')
save = open(f'Result/{answer["carrier"]}.txt', 'a+')
save.write(str(i) + '\n')
else:
print(f'{red}{answer["number"]} => Die{res}')
dk = open('Result/die.txt', 'a+')
dk.write(str(i) + '\n')
Previously, the API endpoint to perform a numverify scan was as follows.
GET https://apilayer.net/api/validate?access_key=access_key&number=phone_number
This has been changed to the following.
GET https://api.apilayer.com/number_verification/validate?number=phone_number
apikey: access_key
how to fix this?

Update the URL in the code as follows:
phone_number = open(input(f'\n{cy}Enter Phone Number List{res} : '),'r').read().splitlines()
access_key = input(f'\n{yl}Enter Your Access Key {red}[ Numverify ]{res} : ')
print('------------------------------------------------------------------')
headers = {'apikey': access_key}
for i in phone_number :
url = 'https://api.apilayer.com/number_verification/validate?number=' + str(i)
response = requests.get(url, headers=headers)
answer = response.json()
if answer["carrier"] :
print(f'{gr}{answer["number"]}{res}{yl} => {cy}{answer["carrier"]}{res}')
save = open(f'Result/{answer["carrier"]}.txt', 'a+')
save.write(str(i) + '\n')
else:
print(f'{red}{answer["number"]} => Die{res}')
dk = open('Result/die.txt', 'a+')
dk.write(str(i) + '\n')

Related

how to print the exception from exce? My code is in string. It works fine on the correct code snippet. not on error [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 days ago.
This post was edited and submitted for review 4 days ago and failed to reopen the post:
Not suitable for this site
Improve this question
import os
path = "C:\\Users\\Abdul Rafay\\Downloads\\Compressed\\day3_t1\\day3_t1"
file_name = os.listdir(path)
word1 = "email"
word2 = "return"
word3 = "def"
x = ""
y = "5"
for i in file_name:
path1 = os.path.join(path, I)
with open(path1, 'r') as fp:
lines = fp.readlines()
for line in lines:
if line.find(word1) != -1:
print("File: ",path1)
print("Email: ",line.strip("email= "))
elif line.find(word2) != -1 or line.find(word3) != -1:
x += line
if 'def' in x and 'return' in x:
print("Solution(5): ")
exec(x + """
try:
print(solution("""+str(y)+"""))
except Exception as err:
print(err)
""")
print("=========================")
x = ""
#The End---------------------------------------The End
Type 1 (with Error)
Type 2 (No Error)
I am reading the "solution" method from these files. and pass the parameter using exec and execute the function.
But the problem is when there is no error in the code it works fine but if there is a error it doesn't show the exception.
This is the output. when there is error it prints the particular function multiple times.

Create files in a specific directory [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to create a file (.txt) in the data directory but it creates a folder
This is the code I am using
How can I create the file
lenID = abs(len(id) - 5)
nameid = ""
for i in range(lenID):
nameid += "0"
nameid += id
self.pathID = os.getcwd() + "\\Backup\\Data\\" + nameid
self.pathimages = os.getcwd() + "\\Backup\\Data\\" + nameid + "\\Contacts"
pathlogo = os.getcwd() + "\\Backup\\Data\\" + nameid + "\\Logo"
pathimeeting = os.getcwd() + "\\Backup\\Data\\" + nameid + "\\Meeting"
pathnote= os.getcwd() + "\\Backup\\Data\\" + nameid + "\\Notes.txt"
pathID = os.path.join(os.getcwd() + "\\Backup\\Data\\" + nameid)
####### CREATE FOLDER
if not os.path.exists(pathID):
os.mkdir(pathID)
if not os.path.exists(self.pathimages):
os.mkdir(self.pathimages)
if not os.path.exists(pathlogo):
os.mkdir(pathlogo)
if not os.path.exists(pathimeeting):
os.mkdir(pathimeeting)
if not os.path.exists(pathnote):
os.mkdir(pathnote)
self.ui.label_2.setText(self.pathID)
self.Cargar(self.pathimages)
self.Logo(pathlogo)
self.Notes(self.pathID)
os.mkdir() creates a directory, wheras os.mknod() creates a new filesystem node (file), so you should change the applicable function calls to that.
Alternatively, (due to os.mknod() not being great cross-platform), you can open a file for writing then immediately close it again, thus creating a blank file:
with open(pathnote, 'w'): pass

How to use Python requests and looping to write Json files

I have writen some python code o help me pull data from an API. The first version of my program work quite well.
N0w i am trying to develop a more DRY version of the code by introducing functions and loops . I am still new to python.
Your proffesional advice will be really apreciated
import requests
import json
# Bika Lims Authentication details
username = 'musendamea'
password = '!Am#2010#bgl;'
# API url Calls for patients, analysis and cases
patient_url = "adress1"
analysis_url = "adress2"
cases_url = "adress3"
# peform API calls and parse json data
patient_data = requests.get(patient_url, auth=(username, password ))
analysis_data = requests.get(analysis_url, auth=(username, password ))
cases_data = requests.get(cases_url, auth=(username, password ))
patients = json.loads(patient_data.text)
analysis = json.loads(analysis_data.text)
cases = json.loads(cases_data.text)
# checks for errors if any
print ("Patients")
print (patients['error'])
print (patients['success'])
print (patients['last_object_nr'])
print (patients['total_objects'])
print ("\n Analysis")
print (analysis['error'])
print (analysis['success'])
print (analysis['last_object_nr'])
print (analysis['total_objects'])
print ("\n Cases")
print (cases['error'])
print (cases['success'])
print (cases['last_object_nr'])
print (cases['total_objects'])
# create and save json files for patients, analysis and cases
with open('patients.json', 'w') as outfile:
json.dump(patients['objects'], outfile)
with open('analysis.json', 'w') as outfile1:
json.dump(analysis['objects'], outfile1)
with open('cases.json', 'w') as outfile2:
json.dump(cases['objects'], outfile2)
The Above code works pretty well but my challenge is making the code DRY. somehow the loop breaks when i change the following section
your_domain = "10.0.0.191"
data_types = ['patients', 'analysis', 'cases']
checkers = ['error', 'success', 'total_objects']
urls = []
data_from_api = []
# API url Call
base_url = "http://" + your_domain + "/##API/read?"
page_size = "1000000000000000000"
patient_url = base_url + "catalog_name=bika_patient_catalog&page_size="
+ page_size
analysis_url = base_url + "portal_type=AnalysisRequest&
review_state=published&page_size=" + page_size
cases_url = base_url + "portal_type=Batch&page_size=" + page_size
urls.append(patient_url)
urls.append(analysis_url)
urls.append(cases_url)
# peform API calls and parse json data
def BikaApiCalls(urls, username, password):
for i in len(urls):
data_ = requests.get(urls[i - 1], auth = (username, password))
print (data_types[i] + " ~ status_code: ")
print (data_.status_code + "\n")
data_from_api.append(json.loads(data_.text))
for val in len(checkers):
print (data_from_api[i][val])
BikaApiCalls(urls, username, password)
# Write JSON files
def WriteJson(data_types, data_from_api):
for i in len(data_from_api):
with open(data_types[i] + '.json', 'w') as outfile:
json.dump(data_from_api[i]['objects'], outfile)
WriteJson(data_types, data_from_api)
Where am I getting it wrong. I tried some debugging but i ca seen to get through. Id really appreciate your help.
Thanks in advance :)

Convert Python Strings into Json

I'm trying to write a program that allows a user to input Questions and Answer for a multi-choice quiz. The questions and answers need to be written to a file in json format.
So far I have code that will ask the user for a Question, the correct answer to the question, then 3 incorrect answers, and write all the strings to a file. But I don't know how to convert the strings to json so they can be used in the Quiz.
The Code I have so far is:
def addToList(filename, data):
question = input('Add Question: ') # prompt user to type what to add
correct = input('Add Correct Answer: ')
wrong1 = input('Add 1st Incorrect Answer: ')
wrong2 = input('Add 2nd Incorrect Answer: ')
wrong3 = input('Add 3rd Incorrect Answer: ')
question = question + '\n' # add a line break to the end
correct = 'correct: ' + correct
wrong1 = 'wrong1: ' + wrong1
wrong2 = 'wrong2: ' + wrong2
wrong3 = 'wrong3: ' + wrong3
data.append(question) # append the question
data.append(correct)
data.append(wrong1)
data.append(wrong2)
data.append(wrong3)
f = open(filename, 'a') # open the file in append mode
f.write(question) # add the new item to the end of the file
f.write(correct)
f.write(wrong1)
f.write(wrong2)
f.write(wrong3)
f.close()
Sorry, I know this is a newbie problem but I'm totally lost here and can't find any examples of user input being put into Json.
First you build a dictionary, then convert it to JSON.
Like this:
import json
# (...)
correct = 'correct: ' + correct
wrong1 = 'wrong1: ' + wrong1
wrong2 = 'wrong2: ' + wrong2
wrong3 = 'wrong3: ' + wrong3
dic = {'correct': correct, 'wrong1': wrong1, 'wrong2': wrong2, 'wrong3': wrong3}
json_str = json.dumps(dic)

Currently listed solution to .replace() not fixing my issue

I have just tried the syntax suggested on a previous question similar to mine and it has not worked for me. I have tried:
newvar = str(oldvar)
newvar = newvar.replace('\r', '').replace('\n', ' ')
and I have tried:
newvar = oldvar.replace('\r', '').replace('\n', ' ')
My full (relevant) sections of code are here:
URLS = myurls2.values()
# Retrieve a single page and report the url and contents
def load_url(key, url, timeout):
conn = urllib.request.urlopen(url, timeout=timeout)
return conn.readall()
# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
# Start the load operations and mark each future with its URL
future_to_url = {executor.submit(load_url, key, url, 60): (key, url)
for key, url in myurls2.items()}
c = 0
for future in concurrent.futures.as_completed(future_to_url):
key, url = future_to_url[future]
try:
data = str(future.result())
data2 = str(data)
data2 = data2.replace('\r', '').replace('\n', ' ')
print(data2)
d = open(filepath,"w")
d.write(data2)
d.close()
Dictionary values are converted to urls that are submitted to the relevant website then at the end I wish to convert them into a string and remove the characters listed in the replace statement.
Thanks

Categories