Search code examples
pythonpython-3.xcsvdelimitercsvreader

TypeError - read csv functionality


I am getting a Type error when reading a csv file with a bell character as a separator. I don't want to use the pandas and need to utilize the csv libraries for this issue.

Sample header:

["header1", "header2", "header3"]

Data types

[integer, string, integer]

Sample data:

"2198"^G"data"^G"x"
"2199"^G"data2"^G"y"
"2198"^G"data3"^G"z"

Sample code

def main():
    columns = ['col1', 'col2', 'col3']
    try:
        csv_dict_list = []
        with open("bell.csv", "r") as file:
            reader = csv.DictReader(file, delimiter=r'\a', quoting=csv.QUOTE_ALL, skipinitialspace=True, fieldnames=columns)
            for row in reader:
                print(row)
                csv_dict_list.append(row)
    except Exception as e:
        raise Exception("Unable to read file: %s" % e)

I get this error -

TypeError: "delimiter" must be a 1-character string

Bell character reference - https://www.asciihex.com/character/control/7/0x07/bel-bell-alert


Solution

  • you're using the raw prefix for your \a delimiter, which makes it 2 characters (backslash, then a)

    You need to just use delimiter='\a', 1 character, the one which is needed to separate the fields.

    >>> len(r'\a')
    2
    >>> len('\a')
    1
    >>>