In: Computer Science
(Python) This is my code for printing a roster for a team. When I print to the console, it makes the first player's name show up as number 2, and it says [] (its just blank for 1). How can I fix that so the first player's name is 1, not skipping 1 and going to 2.
def file_to_dictionary(rosterFile):
myDictionary={}
myDict=[]
with open(rosterFile,'r') as f:
for line in f:
(num,first,last,position)=line.split()
myDictionary[num]= myDict
myDict=[first, last, position]
print (myDictionary)
return myDictionary
file_to_dictionary((f"../data/playerRoster.txt"))
In this program I see that you are trying to read a file line by line and create a dicitionary out of the data in it. Also, i assume that the data in each line are seperated by spaces, and that is why you are using line.split().
With those assumptions in mind, I see a few logical error in your code.
First, you are opening the file in read mode, that part is correct. But, no where in the entire code, the data in the file is being read. the file pointer is f, use that to read the data, and split them across newlines. You will get a list of all the lines in the file. You can later use this list to access each line of the file.
Then,check the for loop. You cannot loop over a file pointer. Rather we will loop over the list we have created in the previous step.
Finally, don't assign myDict to myDictionary[num] and change it later. First change the myDict list and then assign it to myDictionary[num]. This is the reason why the first line of the file is not showing up in myDictionary.
modified program:
def file_to_dictionary(rosterFile):
myDictionary={}
with open(rosterFile,'r') as f:
data = f.read().split('\n')
for line in data:
(num,first,last,position)=line.split()
myDict=[first, last, position]
myDictionary[num]= myDict
print (myDictionary)
return myDictionary
file_to_dictionary((f"../data/playerRoster.txt"))
If your issue is still not fixed, please reach out to me in comments.