Writing data to multiple folders in Python
Question:
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
Answers:
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))
The writer.writerow
expects an iterable, not an integer. You can fix it by changing that line to this:
writer.writerow(str(A))
More information on the documentation: https://docs.python.org/3/library/csv.html#csv.csvwriter.writerow
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
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))
The writer.writerow
expects an iterable, not an integer. You can fix it by changing that line to this:
writer.writerow(str(A))
More information on the documentation: https://docs.python.org/3/library/csv.html#csv.csvwriter.writerow