Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

Hi i have this problem quite long and have no idea how to deal with it. I want to program run sth like this :

  • user write command in discord with argument (amount)
  • discord function will call read_coupon function with written argument
  • read_coupon function will open and read lines (depend of amount) and return it from txt file

atm my code ignore user input and return only first line in 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can do something like this:

def read_coupon(amount):
    kody_open = open("kody.txt","r")
    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

You need to remember to close the file in case python fails to automatically close the file. You will also want to add a minimum check between the amount and the list in case the amount specified goes over the length of the list.

Alternatively, you can do something like this with a context manager which will automatically close the file upon exiting the context.

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading