Search code examples
pythonpandascsvexport-to-csv

Python for loop on function with args for csv export


I wrote this function without any arguments at first and it ran fine and could export the values to csv. I then added arguments to this function but now it won't export to csv, though the code returns 0. The function can print and append a list.

def grp(department, group):
    df = pd.DataFrame(data=students, columns=['Name', 'Department', 'Script'])
    df = df[df.Department == department]
    df['Script'] = 'ADD USER ' + df['Name'] + ' TO ' + group
    return df['Script']


with open('output.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    for val in grp('Biology', 'Science'):
        writer.writerow([val])

Solution

  • There's no need for the loop. You're returning a Pandas series from the function, just use its to_csv() method.

    grp('Biology', 'Science').to_csv('output.csv')