简体   繁体   English

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

[英]How to use better 'try' and 'except' in my code?

now i have this code and i need to use better the function try and except and improve the code, like which parts i should change of place 现在我有了这段代码,我需要使用更好的功能try和except并改进代码,例如我应该更改位置的部分

this is the beginning of my code: 这是我的代码的开头:

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

I don't know exactly the objective of the code, however. 我不知道代码的确切目标。

  1. I had to work out how would the file be structured by the code 我必须弄清楚如何通过代码来构造文件
    Correct me if I'm wrong but I believe that the file is meant to have a list of parameters separated by ";" 如果我错了,请更正我,但我认为该文件应包含用“;”分隔的参数列表。 and each line being an entry in that list. 并且每一行都是该列表中的一个条目。
  2. You do nothing with the data, in any case just breaking the file into a list of parameters and sending said list of lists back would be enough for a function and then you could do the separation later 您对数据不执行任何操作,在任何情况下,只要将文件分解为参数列表,然后将所述列表列表发送回就足以实现功能,然后可以稍后进行分离
  3. So that I could see that the code was doing what I wanted I added a print at the end to get the result 这样我就可以看到代码正在执行我想要的操作,我在最后添加了打印以获取结果

This is the code I ended with I tried to explain most of the issues in comment (probably a bad idea and I shall be berated by this till the end of ages) 这是我结束时试图解释注释中大多数问题的代码(可能是一个坏主意,我将以此为荣直到世代相传)

# 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))

For a text file with the format: 对于具有以下格式的文本文件:

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

I got an output in the form of: 我得到以下形式的输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM