0

I need to order a txt file based on the first number in a list which contains both int and str. I opened the file and created a list for each line. Now I am trying to create a new list or dict based on the first item in the list which will always be an int.

The purpose of the first exercise was to receive a txt file and read its contents and create a program for users to select their choice however, the txt was sorted numerically. Which I completed and am using as a base. Now I need to get an unordered txt file and sort them.

My idea was to first create a function to sort or create a new list ordered by the first character of each line, then to create another function to convert it into a dictionary. However, I cannot seem to sort my list.

Note: I understand my sort function is only printing and not returning anything, I did this just to be able to see what I am working with and be able to show you guys where I am stuck on. I also commented out the conv2Dict function because it currently just stores my unsorted list into a dict. However, once I am able to sort the list it should work. I did not include my I/o functions since they do not interfere with the sorting.

from typing import List

def open_file() -> str:
    with open("menu.txt", "r") as file:
        return file.read()

def process_file() -> List[str]:
    optionsList = []
    with open("menu.txt", "r") as file:
        lines = file.readlines()
    for line in lines:
        options_list_unconverted = line.split("-")
        option = options_list_unconverted[0].strip("\n").strip()
        optionsList.append(option)
    print(optionsList)
        
    return optionsList

def sortByFirstCharacter(optionsList:List):
    for i in optionsList:
        print(i[0][0])

# def convertList2Dict(optionsList:List):
#     dict = {str(i): value for i, value in enumerate(optionsList)}
#     print(dict)



optionsList = process_file()
sortByFirstCharacter(optionsList)

menu.txt =
4;Deleta
1;Insere
5;Mostra
3;Exclui
2;Altera

Ken White
  • 123,280
  • 14
  • 225
  • 444
pedroo_
  • 17
  • 6
  • After 30 minutes, it in fact did solve my problem. I didn't understand it at first since it is still quite difficult to grasp some concepts. Thanks for sharing that post. Should I erase this question since I cannot mark it as answered? – pedroo_ Sep 26 '22 at 02:29
  • You can either accept the proposed duplicate, or delete the question. Your choice. Sorry I wasn't able to offer more guidance, as I couldn't exactly tell the structure of `optionsList` and so was just going on the text of your question – Nick Sep 26 '22 at 03:09

0 Answers0