Python Forum
Function throws error but then works?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Function throws error but then works?
#1
This is really strange. The following function gets called, and throws an error and then immediately prints out part of what I want. I don't understand.

def load_track_to_Handi():
	global track_abrev
	global race_number
	
	
	
		
	with open('C://guis/f_racefiles/'+ track_abrev + '.csv', 'r') as track_file:
		
		csv_reader = csv.reader(track_file)
		
		for line  in csv_reader:
			if race_number in  line[1]:
				print(line )
Error message:
Error:
Milford@LAPTOP-3NUEM60C MINGW64 /c/guis $ python testloop.py Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Milford\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__ return self.func(*args) File "testloop.py", line 79, in select_track load_track_to_Handi() File "testloop.py", line 55, in load_track_to_Handi if race_number in line[1]: IndexError: list index out of range ['AP ', '1', 'D', 'C', '13000', '18', '2', '107', '17', '9', '1', '82', '8', '79', '6', '323', '42', '3', 'EYE ON THE FINISH', '17', '0', '0', '3', '0', '5', '0', '1', '0', '2020', '9', '2019', '6', '15', '1', '14', '65', '1320', '1540', '1870', '1800', '1870', '1430', '1540', '1320', '1870', '1800', 'D', 'D', 'T', 'D', 'T', 'D', '1540', 'D', 'T', 'D', '7', '11', '10', '7', '10', '8', '7', '10', '10', '6', '7', '6', '5', '1', '2', '8', '2', '6', '4', '5', '7', '6', '4', '1', '3', '8', '1', '6', '3', '6', '4', '65', '55', '65', '65', '65', '65', '48', '0', 'FOR FILLIES AND MARES THREE YEARS OLD AND UPWARD WHICH HAVE NEVER WON TWO RACES. Three Year Olds; 121 lbs.; Older; 124 lbs. Non-winners Of A Race Since July 13 Allowed 3 lbs. Claiming Price $10;000 (Races Where Entered For $8;000 Or Less Not Considered In Allowances).', 'Clm 10000']
It prints the first line from the file but stops there. Should be another 5 lines printed out based on contents of the file I am accessing. I can't find this problem described anywhere.
Reply
#2
There is a lot of code missing, but in line 13, you seem to
imply that line is a list. The error message says that line[1] does not exist.
line is a line of text, not an array in the way you use it.

Paul
It is more important to do the right thing, than to do the thing right.(P.Drucker)
Better is the enemy of good. (Montesquieu) = French version for 'kiss'.
Reply
#3
Thank you. I will see how I can manipulate that then. I did watch a video and a guy did exactly what I am trying to do, and he had no problem.
Reply
#4
look at the file you are working with - there is something in the format that is not what you expect - e.g. empty lines. what is printed doesn't really look like coming from real csv file
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
I am writing a dictionary to csv file with DictWriter and trying to read back the files I have written with DictReader. But now I get this error:


$ python testloop.py
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Milford\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "testloop.py", line 80, in select_track
load_track_to_Handi()
File "testloop.py", line 56, in load_track_to_Handi
if i['track'] == 'AP ':
KeyError: 'track'

When I just print the file each line starts with {'AP ': 'AP ', where as when I wrote the file using DictWrite the first fieldname was "track" which is what 'AP ' is the name of the track.
Reply
#6
Obviously you don't write what you think you do
we don't see your current code, or the output
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
I looked in the file. It opens in Excel and each cell has what I wrote in it. But when it get's read by DictReader it's not the same, in as much as the track cell Dictionary "track" is Key and "AP " is the track. But you can see when I read and print it out in the ide, It shows "AP " : "AP " when it should be "track" : "AP "
Reply
#8
well, without seeing your code, ideally with sample input and output, there is little we can help
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#9
Okay. It's just I got chastised the other day for putting too much code up. So here goes.

def load_racefiles() :
    global Race_date
    global master_race_file
    global track_name
    global order
    global h
    global line
    field = ['track','race_number','todays_surface','race_type','todays_purse',
    		'trn_starts_curmeet','trn_wins_curmeet','jock_sts_curmeet','jock_wins_curmeet' ,
    		'trn_starts_prevyear' , 'trn_wins_prevyear','jock_sts_prevyear','jock_wins_prevyear' ,
    		'trn_starts_curyear' ,'trn_wins_curyear','jock_sts_curyear','jock_wins_curyear',
    		'morn_line','horse_name' ,'year_of_birth' ,'hstarts_todays_dist','hwins_todays_dist ' ,
    		'hstarts_todays_track','hwins_todays_track','hstarts_turf','hwins_turf' ,'hstarts_mud' ,
    		'hwins_mud','hstarts_cur_yr','hwins_cur_yr','hstarts_prev_yr','hwins_prev_yr','hstarts_life' ,
    		'hwins_life','days_since','power_rating' ,'dist_yards1','dist_yards2','dist_yards3',
    		'dist_yards4','dist_yards5','dist_yards6' ,'dist_yards7' ,'dist_yards8','dist_yards9',
    		'dist_yards10','surface1' ,'surface2','surface3' ,'surface4','surface5' ,'surface6' ,
    		'surface7' ,'surface8','surface9' ,'surface10','entrants1','entrants2' ,'entrants3',
    		'entrants4' ,'entrants5','entrants6','entrants7','entrants8' ,'entrants9','entrants10',
    		'first_call1' ,'first_call2','first_call3' ,'first_call4' ,'first_call5' ,'first_call6',
    		'first_call7','first_call8','first_call9' ,'first_call10','second_call1' ,'second_call2',
    		'second_call3','second_call4' ,'second_call5','second_call6' ,'second_call7' ,'second_call8',
    		'second_call9','second_call0','finish_Position' ,'last_peed','speed_2back' ,'speed_3back' ,
    		'bestSpeed_Life','bestSpeed_Fasttrack' ,'bestSpeed_turf','bestSpeed_offtrack' ,'bestSpeed_dist',
    		'race_conditions' ,'todays_race_classification' 



    ]
    order= []
    track_name = " "
    master_race_file = []
    h = {}
    count = 0
    df_filespath = ('C://guis/f_racefiles/')
    rows = 100
    columns = 100
    horse_array = [0 for i in range(rows)] 
    filename = StringVar()
    f_name = StringVar()
    line = ()
     
    fd =    open("dirpath", "r") 
    file_dir = (fd.read())
    fd.close()
    os.chdir(file_dir)
    print(file_dir)
    for f in os.listdir(file_dir): 
        file_name, file_ext = os.path.splitext(f)
        f_name = file_name + file_ext
        file_name = file_name.strip()[3:]
        line_counter = 0
        if file_name == Race_date and file_ext == ".jcp":
            with open(f_name, "r") as csv_file:
                csv_reader = csv.reader(csv_file)
                 
                for line in csv_reader:
                    if line_counter > 0: 
                        track_name = line[0]
                    #os.chdir(df_filespath) 
                        filename = df_filespath + track_name + '.csv'               		
                        with open(filename, 'a') as csv_file:
                            d_writer = csv.DictWriter(csv_file, fieldnames = field)	                   
                            d_writer.writerow(h)                   	                    		                        
                    line_counter+= 1								                    		
                 
                     
                    h = {'track' : line[0],
                    'race_number' : line[2], 
                    'todays_surface' : line[6],
                     'race_type' : line[8], 
					'todays_purse' : line[11],
					 'trn_starts_curmeet' : line[28],
					'trn_wins_curmeet' : line[29],
					'jock_sts_curmeet' : line[34],
					'jock_wins_curmeet' : line[35],
					'trn_starts_prevyear' : line[1151],
					'trn_wins_prevyear' : line[1152],
					'jock_sts_prevyear' : line[1161],
					'jock_wins_prevyear' : line[1162],
					'trn_starts_curyear' : line[1146],
					'trn_wins_curyear' : line[1147],
					'jock_sts_curyear' :  line[1156],
					'jock_wins_curyear':  line[1157],
					'morn_line': line[43],
					'horse_name' : line[44],
					'year_of_birth' : line[45],
					'hstarts_todays_dist' : line[64],
					'hwins_todays_dist ' : line[65],
					'hstarts_todays_track' : line[69],
					'hwins_todays_track' :line[70],
					'hstarts_turf' : line[74],
					'hwins_turf' : line[75],
					'hstarts_mud' : line[79],
					'hwins_mud' : line[80],
					'hstarts_cur_yr' : line[84],
					'hwins_cur_yr' : line[85],
					'hstarts_prev_yr' : line[90],
					'hwins_prev_yr' : line[91],
					'hstarts_life' : line[96],
					'hwins_life' : line[97], 
					'days_since' : line[223],
					'power_rating' : line[250],
					'dist_yards1' : line[315],
					'dist_yards2' : line[316],
					'dist_yards3' : line[317],
					'dist_yards4' : line[318],
					'dist_yards5' : line[319],
					'dist_yards6' : line[320],
					'dist_yards7' : line[321],
					'dist_yards8' : line[322],
					'dist_yards9' : line[323],
					'dist_yards10' : line[324],
					'surface1' : line[325],
					'surface2' : line[326],
					'surface3' : line[327],
					'surface4' : line[328],
					'surface5' : line[329],
					'surface6' : line[330],
					'surface7' : line[321],
					'surface8' : line[332], 
					'surface9' : line[333],
					'surface10' : line[334],
					'entrants1' : line[345],
					'entrants2' : line[346],
					'entrants3' : line[347],
					'entrants4' : line[348],
					'entrants5' : line[349],
					'entrants6' : line[350],
					'entrants7' : line[351],
					'entrants8' : line[352],
					'entrants9' : line[353],
					'entrants10' : line[354],
					'first_call1' :  line[575],
					'first_call2' : line[576],
					'first_call3' : line[577],
					'first_call4' : line[578],
					'first_call5' : line[579],
					'first_call6' : line[580],
					'first_call7' : line[581],
					'first_call8' : line[582],
					'first_call9' : line[583],
					'first_call10' : line[584],
					'second_call1' : line[585],
					'second_call2' : line[586],
					'second_call3' : line[587],
					'second_call4' : line[588],
					'second_call5' : line[589],
					'second_call6' : line[590],
					'second_call7' : line[591],
					'second_call8' : line[592],
					'second_call9' : line[593],
					'second_call0' : line[594],
					'finish_Position' : line[615],
					'last_peed' : line[845],
					'speed_2back' : line[846],
					'speed_3back' : line[847],
					'bestSpeed_Life' : line[1327],
					'bestSpeed_Fasttrack' : line[1177],
					'bestSpeed_turf' : line[1178],
					'bestSpeed_offtrack' : line[1179],
					'bestSpeed_dist' : line[1180],
					'race_conditions' : line[15],
					'todays_race_classification' : line[10] 
                     
                     
 
                 
                        }
 
               					
                 
                     
         
             
             
                 
    my_labeldone= Label( text ="Downloading Complete", fg= "black", font = ("sans_serif" , 16)).place(x=500, y=500)




def select_track():
	global ts
	global race_number
	ts = track_listbox.curselection()[0]
	race_number = race_number
	ts = int(ts)
	track_assign()
	
	load_track_to_Handi()


def load_track_to_Handi():
	global track_abrev
	global race_number
	
	
	
		
	with open('C://guis/f_racefiles/'+ track_abrev + '.csv', 'r') as track_file:
		
		csv_reader = csv.DictReader(track_file)
		
		
		for line in csv_reader:
			print(line)
User enters date to handicap then program loads those files and parses the info and writes new files. Then user clicks a race number button and then a track button selecting the race to be handicap and this is where the problem shows up. You can see the printout in previous message. Thanks for the help.
Reply
#10
(Sep-11-2020, 11:30 PM)Milfredo Wrote: Okay. It's just I got chastised the other day for putting too much code up. So here goes.

No one wants to look through a thousand lines of irrelevant code. At the same time, it's impossible to help if we can't see what you're doing. Even the code itself isn't always enough if there's some quirk of the input data that's the problem.

Best is you make your program modular enough that when you have a problem, you can track down the error in just one part and post an easily-reproducible example. The best examples are short and can be pasted onto some other machine and run to show the problem.


That said, I don't understand this at all. Your trace shows if i['track'] == 'AP ': threw a problem in load_track_to_Handi. But that line doesn't appear in that function or elsewhere in your code. Is the version you pasted the same one that generated that error? Right now it looks like that function does nothing but print some lines to stdout. It doesn't return any data.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  DF.groupby(col).min works, mean gets a "not implemented" error samgardner5 3 493 Feb-29-2024, 06:13 PM
Last Post: deanhystad
  Pandas - error when running Pycharm, but works on cmd line zxcv101 1 1,372 Jun-18-2022, 01:09 PM
Last Post: snippsat
  pymysql: insert query throws error wardancer84 12 4,603 Jan-28-2022, 06:48 AM
Last Post: wardancer84
  pyarrow throws oserror winerror 193 1 is not a valid win32 application aupres 2 3,797 Oct-21-2020, 01:04 AM
Last Post: aupres
  delete a file works but with error Leon79 4 2,944 Jul-14-2020, 06:51 AM
Last Post: snippsat
  python/winrt Bluetooth.GenericAttributProfile CreateAsync(GUID) method throws Not Imp pbvinoth 0 2,144 Jul-08-2020, 04:27 AM
Last Post: pbvinoth
  Can't find error in code but Python throws exception Sandwich_masterX 3 2,950 Oct-09-2018, 01:38 AM
Last Post: ichabod801
  Need to understand the way enumerate() function works abhishekambastha 2 2,489 Sep-16-2018, 08:21 PM
Last Post: snippsat
  Jython code throws ImportError when invoked from a Java jar dchucks 6 7,128 Aug-02-2018, 05:09 AM
Last Post: dchucks
  Script works ok on windows but gives error on ubuntu papampi 3 4,055 Oct-11-2017, 04:17 PM
Last Post: papampi

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020