Python Forum
How do I use tabs and spaces? (how to resolve error TabError: inconsistent)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I use tabs and spaces? (how to resolve error TabError: inconsistent)
#1
Hello I like to import transactions into Gnu-Cash. By default my bank export is not suitable for Gnu-cash. To make it suitable I need to run it through a Python script. I am using this script below that I found on the internet. I assume that I can use this script because it was publicly available. I was not able to approach the author of the script.

While running the script it give the error TabError: inconsistent use of tabs and spaces in indentation

So I replaced all the tabs with spaces, but that gave a error that said that I had to use spaces.

I am not a programmer; my goals is to use this script to import data into Gnu Cash. I hope someone can help me to run this script, so I can start using Gnu-cash.




###################################
# Name script: knab.py            #
# Parameter  : Input file         #
# Author     : Bastiaan Krijgsman #
# Version    : 0.1                #
# Date       : 03-05-2017         #
###################################  

from datetime import datetime
import sys, csv, os

class Bank:
	ifname = ""
	ofname = ""

	def __init__(self,ifile):
		self.ifname = ifile
		self.ofname = str(os.path.splitext(ifile)[0]) + "_" + str(datetime.now().year) + ".csv"

        def gencsvk(self):	
		ifile = open(self.ifname,"rb")
		reader = csv.reader(ifile,delimiter=';')

		ofile = open(self.ofname,"wb")
		writer = csv.writer(ofile,delimiter=',',quotechar='"',quoting=csv.QUOTE_ALL)
		writer.writerow(["Rekening","Datum","Omschrijving","Toelichting","Opname","Storting"])

		## "Rekeningnummer","Transactiedatum","Valutacode","CreditDebet","Bedrag","Tegenrekeningnummer","Tegenrekeninghouder","Valutadatum;
		## Betaalwijze;Omschrijving;Type betaling;Machtigingsnummer;Incassant ID;Adres;
                reader.next()
                reader.next()
                
		for row in reader:
                        
			rekening = row[0]
			datum = row[1]
			#omschrijving = row[10] + " " + row[11] + " " + row[12] + " " + row[13] + \
			#	" " + row[14] + " " + row[15] + " " + row[16] + " " + row[17] + \
			#	" " + row[18]
                        omschrijving = row[9]
			opname = 0
			storting = 0
			toelichting = row[5] + " " + row[6] + " " + row[8] + " " + row[13] 
			if row[3] == "D":
				opname = row[4]
			if row[3] == "C":
				storting = row[4]


			nrow = rekening,datum,omschrijving,toelichting,opname,storting
			print row[4]+ " " + row[6]
			writer.writerow(nrow)

bank = Bank(sys.argv[1])
bank.gencsvk()
if len(sys.argv) < 2:
        print "No input file name given!"
        exit()
Import.csv
KNAB EXPORT;;;;;;;;;;;;;;;;
Rekeningnummer;Transactiedatum;Valutacode;CreditDebet;Bedrag;Tegenrekeningnummer;Tegenrekeninghouder;Valutadatum;Betaalwijze;Omschrijving;Type betaling;Machtigingsnummer;Incassant ID;Adres;Referentie;Boekdatum;
"NL00KNAB0000000000";"06-05-2021";"EUR";"D";"115,89";"NL47RABSDFE64";"AF74 B.V.";"06-05-2021";"iDEAL";"Siet et al AF74 B.V.";"";"";"";"";"C1E0634ZJ";"06-05-2021";
"NL00KNAB0000000000";"06-05-2021";"EUR";"C";"150";"5775SDF39";"Kees de Leeuw";"06-05-2021";"Ontvangen betaling";"";"";"";"";"";"C1E06423VPZK";"06-05-2021";
"NL00KNAB0000000000";"03-05-2021";"EUR";"D";"1,85";"BE85739SDF55506";"Alipay";"03-05-2021";"iDEAL";"Hk E-Commerce";"";"";"";"";"C1E023405B";"03-05-2021";
"NL00KNAB0000000000";"20-04-2021";"EUR";"D";"3,39";"BE85739SD55506";"FS Services S.A.";"21-04-2021";"iDEAL";"Aly EUROPE LTD S.A";"";"";"";"";"C1D20werXHI";"20-04-2021";
Reply
#2
I think I have fixed the indentation
###################################
# Name script: knab.py            #
# Parameter  : Input file         #
# Author     : Bastiaan Krijgsman #
# Version    : 0.1                #
# Date       : 03-05-2017         #
###################################

from datetime import datetime
import sys
import csv
import os


class Bank:
    ifname = ""
    ofname = ""

    def __init__(self, ifile):
        self.ifname = ifile
        self.ofname = str(os.path.splitext(ifile)[0]) + "_" + str(datetime.now().year) + ".csv"

    def gencsvk(self):  # indentation was wrong on this line
        ifile = open(self.ifname, "rb")
        reader = csv.reader(ifile, delimiter=';')

        ofile = open(self.ofname, "wb")
        writer = csv.writer(ofile, delimiter=',',
                            quotechar='"', quoting=csv.QUOTE_ALL)
        writer.writerow(["Rekening", "Datum", "Omschrijving",
                        "Toelichting", "Opname", "Storting"])

        # "Rekeningnummer","Transactiedatum","Valutacode","CreditDebet","Bedrag","Tegenrekeningnummer","Tegenrekeninghouder","Valutadatum;
        # Betaalwijze;Omschrijving;Type betaling;Machtigingsnummer;Incassant ID;Adres;
        reader.next()  # indentation was wrong on this line
        reader.next()  # indentation was wrong on this line

        for row in reader:

            rekening = row[0]
            datum = row[1]
            # omschrijving = row[10] + " " + row[11] + " " + row[12] + " " + row[13] + \
            #   " " + row[14] + " " + row[15] + " " + row[16] + " " + row[17] + \
            #   " " + row[18]
            omschrijving = row[9]  # indentation was wrong on this line
            opname = 0
            storting = 0
            toelichting = row[5] + " " + row[6] + " " + row[8] + " " + row[13]
            if row[3] == "D":
                opname = row[4]
            if row[3] == "C":
                storting = row[4]

            nrow = rekening, datum, omschrijving, toelichting, opname, storting
            print row[4] + " " + row[6]
            writer.writerow(nrow)


bank = Bank(sys.argv[1])
bank.gencsvk()
if len(sys.argv) < 2:
    print "No input file name given!"
    exit()
Note: This code has python 2 prints, if you are running this in python 3 the prints will need changing.
for example
print "No input file name given!"
will need changing to
print("No input file name given!")
Reply
#3
Now it it gives the IndexError: list index out of range line 59
bank = Bank(sys.argv[1])
Reply
#4
When you run the program you need to pass an argument. The program checks this, but in the wrong place. Your code should look like this:
if len(sys.argv) < 2:
    print "No input file name given!"
    exit()
bank = Bank(sys.argv[1])
bank.gencsvk()
Now if you forget to provide a filename you will get the informative message "No input file name given!" instead of an obscure error message about index out of range.

To use this program you will use a command like "python knab.py somefilename" where "somefilename" is the name of a file that appears to contain transactions.
Reply
#5
Running the commando python knab.py import.csv gave the error.

Traceback (most recent call last):
File "C:\TMP\knab.py", line 63, in <module>
bank.gencsvk()
File "C:\TMP\knab.py", line 30, in gencsvk
writer.writerow(["Rekening", "Datum", "Omschrijving",
TypeError: a bytes-like object is required, not 'str'



I use Python 3.9.5 on Windows 10, also the the csv has two more columns (Referentie;Boekdatum;)


###################################
# Name script: knab.py            #
# Parameter  : Input file         #
# Author     : Bastiaan Krijgsman #
# Version    : 0.1                #
# Date       : 03-05-2017         #
###################################
 
from datetime import datetime
import sys
import csv
import os
 
 
class Bank:
    ifname = ""
    ofname = ""
 
    def __init__(self, ifile):
        self.ifname = ifile
        self.ofname = str(os.path.splitext(ifile)[0]) + "_" + str(datetime.now().year) + ".csv"
 
    def gencsvk(self):  # indentation was wrong on this line
        ifile = open(self.ifname, "rb")
        reader = csv.reader(ifile, delimiter=';')
 
        ofile = open(self.ofname, "wb")
        writer = csv.writer(ofile, delimiter=',',
                            quotechar='"', quoting=csv.QUOTE_ALL)
        writer.writerow(["Rekening", "Datum", "Omschrijving",
                        "Toelichting", "Opname", "Storting"])
 
        # "Rekeningnummer","Transactiedatum","Valutacode","CreditDebet","Bedrag","Tegenrekeningnummer","Tegenrekeninghouder","Valutadatum;
        # Betaalwijze;Omschrijving;Type betaling;Machtigingsnummer;Incassant ID;Adres;
        reader.next()  # indentation was wrong on this line
        reader.next()  # indentation was wrong on this line
 
        for row in reader:
 
            rekening = row[0]
            datum = row[1]
            # omschrijving = row[10] + " " + row[11] + " " + row[12] + " " + row[13] + \
            #   " " + row[14] + " " + row[15] + " " + row[16] + " " + row[17] + \
            #   " " + row[18]
            omschrijving = row[9]  # indentation was wrong on this line
            opname = 0
            storting = 0
            toelichting = row[5] + " " + row[6] + " " + row[8] + " " + row[13]
            if row[3] == "D":
                opname = row[4]
            if row[3] == "C":
                storting = row[4]
 
            nrow = rekening, datum, omschrijving, toelichting, opname, storting
            print(row[4] + " " + row[6])
            writer.writerow(nrow)
 
 
if len(sys.argv) < 2:
    print("No input file name given!")
    exit()
bank = Bank(sys.argv[1])
bank.gencsvk()
Reply
#6
(May-20-2021, 04:46 PM)Onanism Wrote: writer.writerow(["Rekening", "Datum", "Omschrijving",
TypeError: a bytes-like object is required, not 'str'
(May-20-2021, 04:46 PM)Onanism Wrote:         ofile = open(self.ofname, "wb")

Well that is weird. I'm not sure but I see you are opening the outputfile as "wb" (= write binary). Perhaps you should open the file as "w" instead.
Reply
#7
(May-20-2021, 04:46 PM)Onanism Wrote: TypeError: a bytes-like object is required, not 'str'
When you make writer it's bytes because of wb.
Then nrow need to bytes as can not mix string and bytes one of the big changes when moving to Python 3 from 2.
So convert before write.
>>> nrow = 'hello world'
>>> type(nrow)
<class 'str'>
>>> nrow = nrow.encode() # Same as encode('utf-8')
>>> type(nrow)
<class 'bytes'>
The other way is to make like this with w and use encoding(default is utf-8),but should specify like this as eg OS can mess it some times.
ofile = open(self.ofname, "w", encoding='utf-8')
writer = csv.writer(ofile, delimiter=',', 
Reply
#8
I have replace line 27 ofile = open(self.ofname, "wb") with

ofile = open(self.ofname, "w", encoding='utf-8')
No I am getting the error's

Traceback (most recent call last):
File "c:\TMP\knab.py", line 63, in <module>
bank.gencsvk()
File "c:\TMP\knab.py", line 35, in gencsvk
reader.next() # indentation was wrong on this line
AttributeError: '_csv.reader' object has no attribute 'next'



I do not understand the how to use to code below. I am not a programmer, My goal is to make this script to work with Gnu Cash

>>> nrow = 'hello world'
>>> type(nrow)
<class 'str'>
>>> nrow = nrow.encode() # Same as encode('utf-8')
>>> type(nrow)
<class 'bytes'>
Reply
#9
(May-21-2021, 06:43 PM)Onanism Wrote: AttributeError: '_csv.reader' object has no attribute 'next'
Because that's is old Python 2 code .next() have been change to next().
So it should be.
next(reader)  # indentation was wrong on this line
next(reader)  # indentation was wrong on this line
(May-21-2021, 06:43 PM)Onanism Wrote: I do not understand the how to use to code below. I am not a programmer, My goal is to make this script to work with Gnu Cash

It was demo of how to use encode() when you usewb in original code.
Then all need to be bytes,can not be string.
# line 30
writer.writerow([b"Rekening", b"Datum", b"Omschrijving",
                        b"Toelichting", b"Opname", b"Storting"])

# Line 56
writer.writerow(nrow.encode())
Reply
#10
I have edit the code now it gives the error

Error:
c:\tmp>python file.py import.csv Traceback (most recent call last): File "c:\tmp\file.py", line 62, in <module> bank.gencsvk() File "c:\tmp\file.py", line 30, in gencsvk writer.writerow([b"Rekening", b"Datum", b"Omschrijving", TypeError: a bytes-like object is required, not 'str'
###################################
# Name script: knab.py            #
# Parameter  : Input file         #
# Author     : Bastiaan Krijgsman #
# Version    : 0.1                #
# Date       : 03-05-2017         #
###################################
 
from datetime import datetime
import sys
import csv
import os
 
 
class Bank:
    ifname = ""
    ofname = ""
 
    def __init__(self, ifile):
        self.ifname = ifile
        self.ofname = str(os.path.splitext(ifile)[0]) + "_" + str(datetime.now().year) + ".csv"
 
    def gencsvk(self):  # indentation was wrong on this line
        ifile = open(self.ifname, "rb")
        reader = csv.reader(ifile, delimiter=';')
 
        ofile = open(self.ofname, "wb")
        writer = csv.writer(ofile, delimiter=',',
                            quotechar='"', quoting=csv.QUOTE_ALL)
        writer.writerow([b"Rekening", b"Datum", b"Omschrijving",
                        b"Toelichting", b"Opname", b"Storting"])
 
        # "Rekeningnummer","Transactiedatum","Valutacode","CreditDebet","Bedrag","Tegenrekeningnummer","Tegenrekeninghouder","Valutadatum;
        # Betaalwijze;Omschrijving;Type betaling;Machtigingsnummer;Incassant ID;Adres;
        next(reader)  # indentation was wrong on this line
        next(reader)  # indentation was wrong on this line
 
        for row in reader:
 
            rekening = row[0]
            datum = row[1]
            # omschrijving = row[10] + " " + row[11] + " " + row[12] + " " + row[13] + \
            #   " " + row[14] + " " + row[15] + " " + row[16] + " " + row[17] + \
            #   " " + row[18]
            omschrijving = row[9]  # indentation was wrong on this line
            opname = 0
            storting = 0
            toelichting = row[5] + " " + row[6] + " " + row[8] + " " + row[13]
            if row[3] == "D":
                opname = row[4]
            if row[3] == "C":
                storting = row[4]
 
            nrow = rekening, datum, omschrijving, toelichting, opname, storting
            print(row[4] + " " + row[6])
            writer.writerow(nrow.encode())
 
if len(sys.argv) < 2:
    print("No input file name given!")
    exit()
bank = Bank(sys.argv[1])
bank.gencsvk()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with removing spaces and tabs from a string msqpython 14 3,914 Jan-21-2021, 10:48 PM
Last Post: deanhystad
  How Can I Resolve This Error JayJayOi 10 7,311 Jan-18-2018, 02:59 PM
Last Post: JayJayOi

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020