keta
keta

Reputation: 5

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].

Upvotes: 0

Views: 971

Answers (1)

Zhenhir
Zhenhir

Reputation: 1238

Your row needs to be a list of 3 items before you write it.

I also want to point out that you are running this function twice, the row = call is completely redundant in the original code.

        for i in range(rowNumber):
            row = [random_category(0,10), random_float(0,10), random_float(0,10)]
            writer.writerow(row)

Is probably what you want.

Also:

columnNumber = 3

is doing nothing since you never refer to it.

Upvotes: 2

Related Questions