Python Forum
Problem with csv - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Problem with csv (/thread-32939.html)



Problem with csv - giorgosmarga - Mar-17-2021

def printGames():
    with open("boardgames.csv", 'r') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            print(row)
            # print(line['title'] + '  ' + line['time'] +
            #     '  ' + line['age'] + "  " + line['players'])
        csvfile.close()
class Game:
    def __init__(self, title, players, age, time):
        self.title = title
        self.players = players
        self.age = age
        self.time = time

    def add_game(self):
        
        with open("boardgames.csv", 'w') as csvfile:
            fieldnames = ['title', 'time', 'age', 'players']
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
            writer.writerow({'title': str(self.title), 'time': str(self.time),
                             'age': str(self.age), 'players': str(self.players)})
            csvfile.close()
I have a problem with this code.
The print function doesnt work for some reason and in add_game if instead of w i type a, the programm doesnt store the dict properly why is that. Do i have a mistake or tehre is a bug with csv?


RE: Problem with csv - Larz60+ - Mar-18-2021

There are a couple of possibilities here.
Does your csv file have a header? If not, you cannot use DictReader
I think that your print function is never reached.
Add immediately after line3:
print(f"csv file contains {len(list(reader))}")
run it and see how many records are found.


RE: Problem with csv - giorgosmarga - Mar-18-2021

(Mar-18-2021, 03:02 AM)Larz60+ Wrote: There are a couple of possibilities here.
Does your csv file have a header? If not, you cannot use DictReader
I think that your print function is never reached.
Add immediately after line3:
print(f"csv file contains {len(list(reader))}")
run it and see how many records are found.


Can i have a function that writes the header at the beggining of the program? or every time i add a new dict i need to write the headers?


RE: Problem with csv - Larz60+ - Mar-18-2021

you can place the header in a list,
then use csv reader (not DictReader)
an example of using zip would be:
    header = ['col1', 'col2', 'col3', ...] # replace with actual column names
    with open("boardgames.csv", 'r') as csvfile:
        reader = csv.reader(csvfile)
        for xrow in reader:
            row = dict(zip(header, xrow))
            ...
the output looks like a json file would be a better choice than your method.


RE: Problem with csv - giorgosmarga - Mar-18-2021

(Mar-18-2021, 10:11 AM)Larz60+ Wrote: you can place the header in a list,
then use csv reader (not DictReader)
an example of using zip would be:
    header = ['col1', 'col2', 'col3', ...] # replace with actual column names
    with open("boardgames.csv", 'r') as csvfile:
        reader = csv.reader(csvfile)
        for xrow in reader:
            row = dict(zip(header, xrow))
            ...
the output looks like a json file would be a better choice than your method.

In my opinion a json file would be our best option here, however my exercise needs a csvs file. I actually fixed the problem thank you for your help. I just added a function that initializes the csv and writes the headers, when the program begins. Thanks!