Home > Software engineering >  Writing data to multiple folders in Python
Writing data to multiple folders in Python

Time:09-22

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

CodePudding user response:

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.

CodePudding user response:

The writer.writerow expects an iterable, not an integer, because a CSV row can have multiple values (one for each column).

You can fix it by putting A inside a list:

writer.writerow([A])

More information on the documentation: https://docs.python.org/3/library/csv.html#csv.csvwriter.writerow

  • Related