首页 文章

如何在我的代码中使用更好的'try'和'except'?

提问于
浏览
0

现在我有这个代码,我需要更好地使用函数try和除了和改进代码,像我应该更改的地方部分

这是我的代码的开头:

contador = 0
name = input("Put the name of the file:")
while name != "close":
    validation=0
    try:
        file = open(name,"r",1,"utf-8")
        validation = validation + 1

    except FileNotFoundError:
        validation = validation

    if validation >= 1:
        Games=[]
        countrylist = []
        lines = 0
        File = open(name,"r") 
        line = File.readline().strip()
        while line != "":
            parts= line.split(";")
            country=parts[0]
            game= parts[1]
            sales= int(parts[2])
            price= float(parts[3])
            format= parts[4]
            Games.append(parts)
            countrylist.append(country)
            line = File.readline().strip()
            lines = lines + 1
        contador = contador + 1

1 回答

  • 0

    但是,我不确切地知道代码的目标 .

    • 我必须弄清楚代码如何构造文件
      如果我错了,请纠正我,但我相信该文件的目的是列出由";"分隔的参数列表,每行都是该列表中的一个条目 .

    • 你没有对数据做任何事情,无论如何只是将文件分成一个参数列表并且发回所述列表列表对于一个函数就足够了然后你可以在以后进行分离

    • 因此我可以看到代码正在执行我想要的操作我在最后添加了一个打印来获得结果

    这是我结束的代码,我试图解释评论中的大部分问题(可能是一个坏主意,我会被这个问题直到年底)

    # Why is there a global counter
    # contador = 0
    
    name = None # you need to declare the name before the loop
    
    # check if the name is empty instead of an arbitrary name
    while name != "":
        name = input("Put the name of the file:")
        # have the call defenition of the name in the loop so you can run the
        # loop until the anme is "" (nothing)
        # otherwhise if you don't break on the catch block it will loop forever
        # since the name will be constant inside the loop
    
        try:
            File = open(file=name,encoding="utf-8").read()
            # when using a function and you don't want to use the arguments
            Games=[]
            countrylist = []
            # lines = 0
            lst = File.strip().split("\n") # break the whole text into lines
            for line in lst: # iterate over the list of lines
                # seperate it into a list of data
                parts= line.strip().split(";") #make each line into a list that you can adress
                # elem[0] -> county
                countrylist.append(parts[0]) # here you can just append directly isntead of saving extra variables
                # same as the previous example
                Games.append(parts[1])
                sales= int(parts[2])
                price= float(parts[3].replace(",","."))
                style = parts[4] # format is already an existing function you shoudn't name your variable like that
                # line = File.readline().strip() -> you don't need to prepare the next line since all lines are 
                #                                   already in the array lst
                # lines += 1
                # contador += 1
                # you don't need to count the lines let the language do that for you
                # and why do you need a counter in the first place
                # you were using no for loops or doing any logic based around the number of lines
                # the only logic you were doing is based on their 
                print(parts)
        except FileNotFoundError as e0:
            print("File not found: " + str(e0))
        except ValueError as e1 :
            print("Value Error: " + str(e1))
    

    对于格式为的文本文件:

    Portugal;Soccer;1000;12.5;dd/mm/yyyy
    England;Cricket;2000;13,5;mm/dd/yyyy
    Spain;Ruggby;1500;11;yyyy/dd/mm
    

    我得到了以下形式的输出:

    ['Portugal', 'Soccer', '1000', '12.5', 'dd/mm/yyyy']
    ['England', 'Cricket', '2000', '13,5', 'mm/dd/yyyy']
    ['Spain', 'Ruggby', '1500', '11', 'yyyy/dd/mm']
    

相关问题