'How to write to csv file by column order?
I want to save the values I created randomly in each column of the csv file that will consist of 3 columns.
So the dataset I want to create is as follows:
-Category- -CorrectAnswer- -AnswerTime-
Category 1 17 38
Category 8 8 20
. . .
. . .
I have a function that generates random float values in a specified range:
def random_float(first, last):
x = random.random()
return round(random.uniform(first, last), 0)
I used the same function to create random categories:
def random_category(first, last):
x = random.random()
return "Category " + str(round(random.uniform(first, last), 0))
Here is the function that writes to the first column:
def write_to_csv(file_name, column_header, rowNumber):
columnNumber = 3
with open(file_name, mode='w', newline = '') as f:
writer = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
writer.writerow(column_header)
for i in range(rowNumber):
row = [random_category(0,10) for j in range(1)]
writer.writerow([random_category(0,10)])
column_header = ['Category', 'CorrectAnswer', 'AnswerTime']
rowNumber = 10
write_to_csv('test.csv', column_header, rowNumber)
Result is like that: csv result
I can write values in columns, but I want to write to different columns at the same time. So, I want to use random_category() function for only column[0], and random_float() function for both column[1] and column[2].
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
