Python - Write each item from a dict's key to a new line

Viewed 126

I think this should be fairly simple but I can't find the write solution for my situation. I have dict where each key has a list. For each key in the dict, I want to open a csv file and write each item in each list to a new line. As the program loops through the dict, a new csv file is created for each key, lines for each item in the list for that key are written to a csv, and then the csv closes so the next csv can be created for the next key:

for k, v in Dict.items():
    name = "coQ" + str(k) + ".csv"
    cPath = r"C:\Path"
    coQ = os.path.join(cPath, name)
    company_file = open(coQ, 'w')
    for i in v:
        company_file.write(str(i))
    company_file.close()

This writes the list to a csv but all the list items are on the same line in the csv outputs. I've tried opening with append 'a' but I get the same result and I don't think newline will work as it's not a new line but an item in a list that needs to be written.

1 Answers

Try:

for k, v in Dict.items():
    name = "coQ" + str(k) + ".csv"
    cPath = r"C:\Path"
    coQ = os.path.join(cPath, name)
    company_file = open(coQ, 'w')
    for i in v:
        company_file.write("\n")
        company_file.write(str(i))
    company_file.close()

Or as patrick said:

for k, v in Dict.items():
    name = "coQ" + str(k) + ".csv"
    cPath = r"C:\Path"
    coQ = os.path.join(cPath, name)
    company_file = open(coQ, 'w')
    for i in v:
        company_file.write(str(i)+'\n')
    company_file.close()
Related