Hi i have this problem quite long and have no idea how to deal with it. I want to program run sth like this :
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
You can do something like this:
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
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