简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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