pythoncsvcsvwriter

How to remove spaces between each letter when writing a dictionary to a csv using csv.writer


I've been trying to make a csv reader that will read a large data set, group the same events together, and count up how many times those events happened. I'm using nested dictionaries to do it.

For some reason the formatting is wrong and it keeps adding spaces between every single character in the string I'm writing.

Does anyone know how to remove it?

I've tried a few other things I've seen on here such as changing write to 'wb' and adding a new line argument, but I couldn't get any of them to work.

with open(r'Redacted', 'w') as reportCSV:
    writer = csv.writer(reportCSV, delimiter=' ')
    for dates, info in dict.items():
        for key in info:
            writer.writerow(dates + ':' + key + ':' + str(info[key]))

Solution

  • writerow iterates its row parameter, converts it to a string, applies any needed escapes and uses delimiter as the separator. In your case, it appears as though dates + ':' + key + ':' + str(info[key]) is a string. writerow iterates it character by character and inserts the ' ' delimiter.

    It appears that you want 3 semi-colon separated columns. That third column could iterated directly via a second .items() call. Put them in a list for the writer.

    with open(r'Redacted', 'w') as reportCSV:
        writer = csv.writer(reportCSV, delimiter=':')
        for dates, info in dict.items():
            for key, value in info.items():
                writer.writerow([dates, key, value])