[Python] Reading and writing dictionary

Discussão em 'Python' iniciado por Stack, Abril 20, 2025.

  1. Stack

    Stack Membro Participativo

    So I thought about writing a program that takes a URL address and shortens it. I want the program to be able to write every new URL and store it in a file and generate a new short one and if the user tries to shorten the same address it'll pull out of the dictionary the result the user got last time he put this address. I set the KEY to the full URL and the VALUE to the short version. I tried to do it but when I try to read it gives me this error:

    (key, val) = line.split()
    ValueError: too many values to unpack (expected 2)


    import random
    import string
    import json

    #Default items
    dict_url = {
    'instagramcom/rois..../': "https:/roi.sl/2Ly8PzD",
    'instagramcom/....../': "https://roi.sl/2YqJa12"
    }
    #Updated_dict will be the dict i'll be using to input and output data
    updated_dict = {}
    updated_dict.update(dict_url)
    #writing the default items from dict_url so updated_dict will have something
    with open('UrlDB.txt', 'w') as file_write:
    file_write.write(str(updated_dict))
    updated_dict.update(dict_url)

    #trying to read the file
    with open('UrlDB.txt', 'r') as file_read:
    for line in file_read:
    (key, val) = line.split()
    updated_dict[key] = val



    while True:
    new_url = ""
    exs_url = ""
    base_form = "https:/roi.sl/"
    user_input = input("Please Enter the URL: ")
    if user_input in dict_url:
    exs_url = dict_url.get(user_input)
    print(exs_url)

    break
    else:
    rnd_comb = (random.choices(string.ascii_uppercase + string.ascii_lowercase + string.digits, k=6))
    rnd_comb_str = ''.join(rnd_comb)
    new_url = base_form + rnd_comb_str
    new_item = {
    user_input: (3, new_url)
    }
    file_write.write(str(new_item))
    dict_url.update(new_item)
    print(new_url)
    break

    Continue reading...

Compartilhe esta Página