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

时间:2018-12-08 23:58:52

标签: python

现在我有了这段代码,我需要使用更好的功能try和except并改进代码,例如我应该更改位置的部分

这是我的代码的开头:

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 :(得分:0)

但是,我不完全了解代码的目标。

  1. 我必须弄清楚如何用代码来构造文件。
    如果我写错了,请纠正我,但我认为该文件应包含以“;”分隔的参数列表。并且每一行都是该列表中的一个条目。
  2. 您对数据不执行任何操作,在任何情况下,只要将文件分解为参数列表,然后将所述列表列表发回就足以实现功能,然后可以稍后进行分离
  3. 这样我就可以看到代码正在执行我想要的操作,我在最后添加了打印以获得结果

这是我最后尝试解释注释中大多数问题的代码(可能是一个坏主意,我将以此为荣直到世代相传)

# 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']