想在 .csv 文件的每一行上打印我的 discord.py 机器人的输出

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

disccord.py命令效果很好,它必须打印一个随机大写字符串(长度为“char”)+变量“value”给出的值,x时间由变量“time”决定“。例如:.testjeg Thisisatest 5 3 将输出: XCF 这就是测试 SDE 这个测试 LOP 这是测试 HJK 这个测试 SDE 这个测试

最后我想在 .csv 文件的单行中打印每个输出,但我的代码在每一行中打印第一个输出的每个字母。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'))

你永远不会真正保存你打印的所有行,因为在做 data = ... 时你只是用新的 str 替换它而不是做 data.append。因此,最后,您的 data 变量只是一个带有最后生成的文本的 str

但是为了让 csv 工作,你需要 data 成为一个 two-dimensional 行和列的列表,例如,[[1,2,3], [4,5,6]] 作为 data 将在一行中保存 1,2,3,在另一行中保存 4,5,6

因此,整个代码(如果您使用简单的 open 而不是 Discord-related 逻辑)将是:

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())