Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading