0

Currently been working on a battleships code for my project for advanced higher computing and I'm at the last hurdle. I am trying to import a CSV file named "leaderboard.csv" which contains two columns with set headers in the csv file (Names and Shots) the data inside looks like this.


Names - Shots


Name1 - 19

Name2 - 24

so on... - ...


This section of the code takes in the data and stores all the names in aNames[] and then all the shots in aShots[] It works as planned for aNames all the names are stored inside the array and I can then work with them however the aShots array is completely empty and its the same code more or less with the heading changed and thats it. The code looks like this.

    def ChangeFileToArray():
        from csv import DictReader
        with open("leaderboard.csv") as f:
             #Where "Names" and "Shots" are the names of the headings in the CSV file.
             aNames=[row["Names"] for row in DictReader(f)]
             aShots=[row["Shots"] for row in DictReader(f)]
    f.close
    return aNames, aShots

The output of the file is like so after all the fluff before it.


['Name1', 'Name2', 'Name3', 'Name4']

[]


I have looked up my solution before and many people say to use pandas solution but that isn't an option for me sadly. I would preferably like to keep it within the (imported) csv module. Thanks in advance.

1 Answers1

0

I am not fresh on the DictReader but I would try something along the lines of the code below. If you are iterating through the rows in DictReader handle all of the operations you want for each row at the same time.

aNames = []
aShots = []
for row in DictReader(f):
    aNames.append(row["Names"])
    aShots.append(row["Shots"])
f.close()