如何 运行 python 函数次数与用户输入 + 读取有效行一样多?

How to run python function as many times as user input + read valid lines?

您好,我遇到这个问题很久了,不知道如何处理。我想像这样编程 运行 某事:

atm 我的代码忽略用户输入并且 return 仅在 kody.txt

中的第一行
@client.command()
 async def kody (ctx, amount):
     await ctx.send(read_coupon(int(amount)))   
def read_coupon(amount):
    x_range = range(0,amount,1)
    kody_open = open("kody.txt","r")
    for line_kod in kody_open:
        kody_lista.append(line_kod)
    for x in x_range:
        for element in kody_lista:
            return element
kody.txt
NLZGQEJ32W
NLBH9LBZVP
NLB6DRBZ4Q
NLJ8GWAC8M
NLBH9LBZVP
NLB6DRBZ4Q
NLJ8GWAC8M

你可以这样做:

def read_coupon(amount):
    kody_open = open("kody.txt","r")
    kody_lista = []
    for line_kod in kody_open:
        kody_lista.append(line_kod)
    kody_open.close()
    result = ''
    for i in range(min(len(kody_lista),amount)):
        result += kody_lista[i]
    return result

您需要记得close the file以防python无法自动关闭文件。您还需要在金额和列表之间添加一个最小检查,以防指定的金额超过列表的长度。

或者,您可以使用上下文管理器执行类似的操作,它会在退出上下文时自动关闭文件。

def read_coupon(amount):
    result = ''
    with open("kody.txt","r") as f:
        for line in f:
            result += line
            amount -= 1
            if amount == 0: break
    return result