Skip to content
Advertisement

Writing data to multiple folders in Python

I am trying to write A in multiple folders, namely, 1,2,3,4,5 with file name A.txt. But I am getting an error. How do I fix it?

import os

Runs=5

def function(run):
    from scipy.stats import truncnorm
    import numpy as np
    import csv 
    
    parent_folder = str(run + 1)
    os.mkdir(parent_folder)

    A=3


    ######################################

    with open(os.path.join(parent_folder, rf"A.txt"), 'w+') as f: 
        
        #print("A =",[A])
        writer = csv.writer(f)
        writer.writerow(A)
     


for x in range(Runs):
    function(x)

The error is

in function
    writer.writerow(A)

Error: iterable expected, not int

Advertisement

Answer

There appears to be a dearth of answers explaining what the actual problem is among the possible duplicates on this site, so here goes.

csv.csvwriter.writerow expects an iterable of elements that represents a row of data. It can’t and won’t guess that a single element should be treated specially (what the error is telling you). If you try to pass in something that’s only accidentally an iterable, such as a string, each character will be treated as a separate element. To correctly write a row, wrap it in an iterable, such as a list, tuple, or even generator:

[A]
(A,)
(A for _ in range(1))

A similar thing happens with csv.csvwriter.writerows. The function expects an iterable of rows, which are themselves iterables. A nested list or tuple will do, but you can’t pass in scalars or single-level iterables. In the latter case, iterating over scalar elements and attempting to treat them as rows will result in the same error as you saw, for the same reason.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement