'Would like to print on the output of my discord.py bot on each row of a .csv file

the disccord.py command works good, it has to print a random uppercase string (with length of "char") + the value given by the variable "value, for x time determinated by the variable "time". Ex: .testjeg Thisisatest 5 3 will output: XCF Thisisatest SDE Thisisatest LOP Thisisatest HJK Thisisatest SDE Thisisatest

IN the end i would like to print each output on a single row of .csv file but my code prints each letter of the first output in each row.strong text

@client.command() async def testjeg(ctx, value, times, char):

def random_char(char):
    return ''.join(random.choice(string.ascii_uppercase) for x in range(int(char)))

header = ["J3gged data"]
data = []



for x in range(0, int(times)):
    data = random_char(char) + f" {value}"
    print(data)
buffer = io.StringIO()
writer = csv.writer(buffer)
writer.writerow(header)
writer.writerows(data)
buffer.seek(0) #Don't know why this is here, but it worked...
await ctx.channel.send(file=discord.File(buffer, f'{value}.csv'))


Solution 1:[1]

You never really save all the lines you print, because instead of doing data.append you just replace it with new str when doing data = .... So, in the end, your data variable only is a str with last generated text.

But in order for csv to work, you need data to be a two-dimensional list of rows and columns, so, for example, [[1,2,3], [4,5,6]] as data would save 1,2,3 on one line and 4,5,6 on other line.

So, entire code (if you would use simple open instead of Discord-related logic) would be:

import random, csv, string

def random_char(char):
    return ''.join(random.choice(string.ascii_uppercase) for x in range(int(char)))

header = ["J3gged data"]
data = []

# added these to have code runnable on itself, as well as imports in the beginning
times, char, value = 4, 7, 'test'

for x in range(0, int(times)):
    # note, how here we create list, instead of saving one value,
    # this is because you only have one column like [1] and not [1,2,3] as text I had above
    data.append([random_char(char) + f" {value}"])

with open('newfile.csv', 'w+') as f:
    writer = csv.writer(f)
    writer.writerow(header)
    writer.writerows(data)

with open('newfile.csv') as f:
    print(f.read())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dmig