Created
January 23, 2022 18:45
-
-
Save Lanse505/5ef5ddb27820944e6417055afb34d72d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os.path | |
import json | |
import util | |
if __name__ == '__main__': # Checks if the code is being invoked directly and not as an import | |
field_names = ['username', 'first_name', 'last_name', 'email'] # Default Field Names | |
field_names_sv = ['användarnamn', 'förnamn', 'efternamn', 'epost'] | |
# Get if the user wants to load from the target CSV or the cached JSON | |
get_from_csv = input("Do you want to load from a CSV or from the cached JSON? [CSV, JSON]: ") | |
csv, file = "", "" # Setups empty defaults for csv and file | |
csv_dict = {} # Setups an empty dict to use | |
if get_from_csv.upper() == "CSV": # Checks if the user wanted to load from the CSV | |
csv, file = util.open_csv("./clean.csv", "r+") # Opens the csv | |
for i, row in enumerate(csv): # Iterate over the rows in the csv | |
if i == 0: # If the row is the header row then continue | |
continue # Skip if it's the head column | |
person_dict = {} # Create an empty dictionary for the user | |
for j, name in enumerate(field_names): # Loops over the field_names | |
row_value = row[j] # Get the value from the CSV | |
if row_value is not None: # If the value isn't empty then add it and its value to the new dict | |
person_dict[name] = row[j] # Set the fields of the "person_dict" | |
continue # Continue as to not add double values to the dict | |
person_dict[name] = None # If the value was empty then add an empty field value to the dict | |
csv_dict[row[0]] = person_dict # Set the "person_dict" to the "csv_dict" with the username as key. | |
file.close() # Closes the file reference | |
if os.path.exists('./temp.json'): # Checks if the JSON file already exists | |
with open('./temp.json', "r+", encoding='utf-8-sig') as temp: # Opens the existing temp.json | |
csv_dict = json.load(temp) # Parses the JSON into the csv_dict as a dict object | |
else: | |
with open('./temp.json', "w+", encoding='utf-8-sig') as temp: # Opens a new file | |
json.dump(csv_dict, temp, indent=True, ensure_ascii=False) # Dumps the dict to Json | |
is_first_run = True | |
while True: | |
option = -1 | |
if is_first_run: | |
with open('./temp.json', "r+", encoding='utf-8-sig') as temp: | |
print(temp.read()) | |
print() | |
is_first_run = False | |
while option == -1: | |
print("#####################") | |
print("# 1 - Add Person #") | |
print("# 2 - Remove Person #") | |
print("# 3 - Save File #") | |
print("# 4 - View Person #") | |
print("# 5 - Exit #") | |
print("#####################") | |
valueIn = input("Select your prefered option: ") | |
while not util.is_integer(valueIn) or not util.is_within(int(valueIn), 1, 4): | |
print("Error: Invalid Input, Please enter a number between 1-4") | |
valueIn = input("Select your prefered option: ") | |
option = int(valueIn) | |
if option == 1: | |
option = util.addPerson(csv_dict) | |
input("Press Any Key to Return to Menu") | |
elif option == 2: | |
option = util.removePerson(False, csv_dict) | |
input("Press Any Key to Return to Menu") | |
elif option == 3: | |
print("Flushing JSON to CSV") | |
option = util.flush_to_csv(csv_dict) | |
input("Press Any Key to Return to Menu") | |
elif option == 4: | |
option = util.get_user_data(csv_dict) | |
input("Press Any Key to Return to Menu") | |
elif option == 5: | |
break | |
print() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv | |
import json | |
import re | |
def open_csv(path: str, mode: str): | |
file = open(path, mode, encoding='utf-8-sig') | |
reader = csv.reader(file, delimiter=';') | |
return reader, file | |
def flush_to_csv(csv_dict): | |
with open('./temp.json', "w", encoding='utf-8-sig') as clear: # Clear the json file | |
pass | |
with open('./temp.json', "r+", encoding='utf-8-sig') as flush: | |
json.dump(csv_dict, flush, indent=True, ensure_ascii=False) | |
with open('./temp.json', "r+", encoding='utf-8-sig') as saved: | |
csv_dict = json.load(saved) | |
with open('./labb2_personer_vt22.csv', 'w', newline='') as file: | |
writer = csv.writer(file) | |
writer.writerow(['användarnamn', 'förnamn', 'efternamn', 'epost']) | |
for (key, value) in enumerate(csv_dict.items()): | |
nk, nv = value | |
writer.writerow([nv['username'], nv['first_name'], nv['last_name'], nv['email']]) | |
return -1 | |
def addPerson(csv_dict): | |
username = input("Please enter a username for the person you want to add: ") | |
while not is_regex_compliant(username, r"[hv]\d{2}[a-z]{5}") and username not in csv_dict: | |
print("Invalid input: Please provide a valid username matching the following regex format:") | |
print(r"[[hv]\d{2}[a-z]{5}] - [Example: h00andan]") | |
username = input("Please enter a username for the person you want to add: ") | |
first_name = input("Please enter the first name of the user you want to add: ") | |
while first_name is None or first_name == "": | |
print("Error: Invalid Input - 'First Name' was either of type None or Empty") | |
first_name = input("Please enter the first name of the user you want to add: ") | |
last_name = input("Please enter the last name of the user you want to add: ") | |
while last_name is None or last_name == "": | |
print("Error: Invalid Input - 'First Name' was either of type None or Empty") | |
last_name = input("Please enter the last name of the user you want to add: ") | |
user_dict = {'username': username, 'first_name': first_name, | |
'last_name': last_name, 'email': username + "@du.se" | |
} | |
csv_dict[username] = user_dict | |
return -1 | |
def removePerson(removed, csv_dict): | |
while not removed: | |
username = input("Please enter the username of the User you want to delete: ") | |
if username == "exit": | |
return -1 | |
if username in csv_dict: | |
csv_dict.pop(username) | |
print(f"Removed user: {username}") | |
removed = True | |
else: | |
print(f"Error: User with Username: {username} , Didn't exist!") | |
def get_user_data(csv_data): | |
username = input("Please enter the username of the user you want to view: ") | |
while not is_regex_compliant(username, r"[hv]\d{2}[a-z]{5}"): | |
print(r"Invalid Error: Please input a regex compliant username [[hv]\d{2}[a-z]{5}]: ") | |
username = input("Please enter the username of the user you want to view: ") | |
data = csv_data[username] | |
first_name = data['first_name'] | |
last_name = data['last_name'] | |
email = data['email'] | |
print(f"Printing data for user: {username}") | |
print(f"Username: {username}") | |
print(f"First Name: {first_name}") | |
print(f"Last Name: {last_name}") | |
print(f"Email: {email}") | |
return -1 | |
def is_integer(num): | |
try: | |
int(num) | |
return True | |
except ValueError: | |
return False | |
def is_regex_compliant(testable: str, pattern: str): | |
if re.match(pattern, testable): | |
return True | |
return False | |
def is_within(value, minimum_inclusive, maximum_inclusive): | |
if minimum_inclusive <= value <= maximum_inclusive: | |
return True | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment