pythonpandascsvfilecsvwriter

which variable do I use to write the data to csv file


how would I adjust my code so that I can print the debit and credit to a csv file please.

I've included the code below and am having trouble making sense of what variables to use and where, with the csv module. I've also included the error message I'm currently getting and a sample of the data printed to the screen. It's this data that I'd like to write to file.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul  2 16:23:17 2023

@author: admin
"""

import pandas as pd
import numpy as np
import csv

# read a csv file
bs = pd.read_csv('mar_2022_bs.csv', index_col=False)
pd.options.display.max_rows = 350


# clean the data removing empty fields and replacing with appropriate data if
# necessary
bs["Debit Amount"].fillna(0.0, inplace = True)
bs["Credit Amount"].fillna(0.0, inplace = True)
bs["Transaction Type"].fillna('OSC', inplace = True)


# Filter the debits by taking out the transactions types, descriptions and
# codes that are not required
debit_amount = bs[(bs['Debit Amount'] > 0) & 
    (bs['Transaction Description'] != 'M HART') & 
    (bs['Transaction Type'] != 'TFR') & 
    (bs['Transaction Description'] != 'ADELE WEEKLY') & 
    (bs['Transaction Description'] != 'SAVE THE CHANGE') & 
    (bs['Transaction Description'] != 'MANSELTON STORES') & 
    (bs['Transaction Description'] != 'Netflix.com')]

print(debit_amount[['Transaction Type', 'Transaction Description', 'Debit Amount']])

print('\nTotal for Month: ', debit_amount['Debit Amount'].aggregate(np.sum), '\n')

# Filter the credits by taking out the transactions types, descriptions and
# codes that are not required
credit_amount = bs[(bs['Credit Amount'] > 0) & 
    (bs['Transaction Description'] != 'CLUB LLOYDS WAIVED') & 
    (bs['Transaction Type'] != 'TFR') & 
    (bs['Transaction Type'] != 'BGC')]

print(credit_amount[['Transaction Type','Transaction Description', 'Credit Amount']])

print('\nTotal for Month: ', credit_amount['Credit Amount'].aggregate(np.sum), '\n')

# writing the debit and credit lists to  a csv file

csvfile = 'money_out.csv'
with open(csvfile, 'w', newline='') as debit_amount:
    writer = csv.writer(debit_amount)
    writer.writerow(debit_amount)
    writer.writerows(debit_amount)

Error Message:

Traceback (most recent call last):

  File ~/anaconda3/lib/python3.10/site-packages/spyder_kernels/py3compat.py:356 in compat_exec
    exec(code, globals, locals)

  File ~/my_acc_v1.py:55
    writer.writerow(debit_amount)

UnsupportedOperation: not readable

Screen Output Sample:

    Transaction Type Transaction Description  Credit Amount
2                DEP           MOBILE CHEQUE          20.00
6                FPI            COONEY JAMES          22.00
7                FPI                   GC C1          16.56

Solution

  • with open(csvfile, 'w', newline='') as debit_amount: # <- you are overwriting the DataFrame from further above, you should avoid that
        writer = csv.writer(debit_amount)  
        writer.writerow(debit_amount) # <-- the error occures, because with debit_amount you are passing a fileobject to writerow(); what you probably want to pass is credit_amount
        writer.writerows(debit_amount) # <-- the same error
    

    As a sidenote, instead of using the csv module you could also use the pandas built-in export functionality:

    credit_amount.to_csv(csvfile)