首页 > 解决方案 > 如何在我的代码中使用更好的“尝试”和“除外”?

问题描述

现在我有了这段代码,我需要更好地使用该功能,尝试并改进代码,比如我应该改变哪些部分

这是我的代码的开头:

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

标签: python

解决方案


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

  1. 我必须弄清楚代码如何构造文件
    如果我错了,请纠正我,但我相信该文件应该有一个由“;”分隔的参数列表 并且每一行都是该列表中的一个条目。
  2. 您对数据不做任何事情,无论如何只需将文件分解为参数列表并将所述列表列表发送回对于函数来说就足够了,然后您可以稍后进行分离
  3. 为了让我可以看到代码正在执行我想要的操作,我在最后添加了一个 print 以获得结果

这是我结束的代码

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

推荐阅读