Home > Enterprise >  reading a csv file and printing out rows
reading a csv file and printing out rows

Time:03-18

I have created a csv file with two columns - the subject and the modules. and i want to print out all the modules for the same subject the csv file looks like this csvfile currently my code looks like:

import csv

subject = "Biology"
subject_module = []
with open("SubjectModules.csv", newline="") as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        subject_module_info = []
        subject, module = row
        while (row["Subject"] == subject):
            subject_module_info.append(module)
            subject_module.append(subject_module_info)
    
    print(subject_module)

the output is just [] with no modules stored, how would i fix it?

CodePudding user response:

This would be easier by using pandas.

import pandas as pd
subject = "Biology"
df = pd.read_csv('./SubjectModules.csv')
df = df[df['Subject'] == subject]
module_list = df['Module'].to_list()

CodePudding user response:

I think what you are trying to do may be less complicated than your sample code suggests.

For example, here is some code using a smaller sample version of your SubjectModules.csv file:

import csv
subject = "Biology"
subject_module = []

with open ("SubjectModules.csv", newline = "") as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row)
    print()

with open ("SubjectModules.csv", newline = "") as csvfile:
    reader = csv.DictReader(csvfile)

    for row in reader:
        if (row["Subject"] == subject):
            module = row["Module"]
            subject_module.append(module)

print(subject_module)

It gives this result:

{'Subject': 'Accounting', 'Module': 'foo1'}
{'Subject': 'Accounting', 'Module': 'foo2'}
{'Subject': 'Accounting', 'Module': 'foo3'}
{'Subject': 'Art and Design', 'Module': 'bar1'}
{'Subject': 'Art and Design', 'Module': 'bar2'}
{'Subject': 'Art and Design', 'Module': 'bar3'}
{'Subject': 'Art and Design', 'Module': 'bar4'}
{'Subject': 'Biology', 'Module': 'baz1'}
{'Subject': 'Biology', 'Module': 'baz2'}

['baz1', 'baz2']

It creates and prints a list of all the modules for the given subject ('Biology'). To do this, only some of the variables in your original code were required, and others have been eliminated.

  • Related