Code that modifies a collection while iterating over that same collection can be tricky to get right. Instead, it is usually more straight-forward to loop over a copy of the collection or to create a new collection:
jueves, 28 de noviembre de 2024
domingo, 10 de noviembre de 2024
reading a file
import os
import sys
def search_key_value(file_path, search_key):
# Open and read the file safely using a context manager
with open(file_path, 'r') as file:
lines = file.readlines()
# Create a dictionary from the parsed list
parsed_dict = {line.strip().split(',')[0]: line.strip().split(',')[1] for line in lines}
# Return the value associated with the search key if it exists
return parsed_dict.get(search_key)
# Example usage:
file_path = '/var/www/html/fwlist.conf'
sound_folder = '/var/lib/asterisk/sounds/en/custom/'
search_key = sys.argv[1]
file = search_key_value(file_path, search_key)
if file:
print(f"The value for key '{search_key}' is: {file}")
# Check if the corresponding file exists
file_path = sound_folder + file
print(1 if os.path.isfile(file_path) else 0)
else:
print(f"Key '{search_key}' not found.")
print(0)
domingo, 3 de noviembre de 2024
searching letters on key and values of a dict
>>> c
{'Ambiorix': 'Rodriguez', 'Katherine': 'Maria, 'Rosa: 'Perez'}
>>> [a for a in list(c.keys()) if 'k'.lower() in a.lower()]
['Katherine']
>>> [a for a in list(c.values()) if 'R'.lower() in a.lower()]
['Rodriguez']
sábado, 2 de noviembre de 2024
python-realtime-twilio-transcription
https://github.com/AssemblyAI-Community/python-realtime-twilio-transcription/blob/main/main.py
viernes, 1 de noviembre de 2024
Regular try , exception finally and Custom Exception error.
try:
n = 10
if n < 20:
raise ValueError("n must be at least 20") # Raising a ValueError with a message
except ValueError as e:
print("An error has occurred:", e)
finally:
print("Code completed.")
--------
Custom Exception error.
class CustomError(Exception):
pass
try:
raise CustomError("This is a custom error message.")
except CustomError as e:
print("An error has occurred:", e)
finally:
print("Code completed.")