2

Trying to write to a csv file for an hour. Output problem: Each character has a comma after it. I'm not sure why this is happening since I've done it multiple times before

  id_list = []

    with open(outfile1, 'r') as f:
        reader = csv.reader(x.replace('\0','') for x in f)

        for row in reader:
            temp = row
            try:
                id = temp[3]
                id_list.append(id)

            except (IndexError, csv.Error, KeyError) as e:
                pass

    with open(results1, 'w') as f:
        writer = csv.writer(f)
        for id in id_list:
            try:
                prov_data = getData()
                if prov_data is None:
                    continue
                fab =  prov_data['results'][0]['fab']
                man = prov_data['results'][0]['man']
                serv_type = prov_data['results'][0]['serv']        
                writer.writerows([str(id), str(fab), str(man), str(serv_type)])
            except (IndexError, KeyError,csv.Error) as e:
                pass
0

1 Answer 1

8

Replace writerows with writerow.

The problem is that writerows expects a list of lists, where each inward list is a row to write. Since you're giving it a list of strings, it thinks every character in the string is a column in the csv file.

Note that you're also not using id in your second for loop, and you are opening a file named outfile1 for reading, so you may need to rethink your names here. I would guess you want to replace the 0s in your second for loop with id, but I'm not sure.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.