1

Im trying to make a script for Discord with python. But I have a weird thing with it. When I run this:

x = 1


def main():
    try:
        global x
        NitroCode = open("NitroCode.txt")
        Codes = NitroCode.readlines()
        
        #Url
        url = ("https://discordapp.com/api/v6/entitlements/gift-codes/" + Codes[x] + "?with_application=false&with_subscription_plan=true")
        print(url)
        
        x += 1
        main()
        
    except IndexError:
      print('Done Checking')
      exit()

main()

I get this output

https://discordapp.com/api/v6/entitlements/gift-codes/b
?with_application=false&with_subscription_plan=true
https://discordapp.com/api/v6/entitlements/gift-codes/c
?with_application=false&with_subscription_plan=true
https://discordapp.com/api/v6/entitlements/gift-codes/d
?with_application=false&with_subscription_plan=true
https://discordapp.com/api/v6/entitlements/gift-codes/e
?with_application=false&with_subscription_plan=true
https://discordapp.com/api/v6/entitlements/gift-codes/f
?with_application=false&with_subscription_plan=true
https://discordapp.com/api/v6/entitlements/gift-codes/g
?with_application=false&with_subscription_plan=true
https://discordapp.com/api/v6/entitlements/gift-codes/h
?with_application=false&with_subscription_plan=true
https://discordapp.com/api/v6/entitlements/gift-codes/i
?with_application=false&with_subscription_plan=true
https://discordapp.com/api/v6/entitlements/gift-codes/j
?with_application=false&with_subscription_plan=true
https://discordapp.com/api/v6/entitlements/gift-codes/k?with_application=false&with_subscription_plan=true
Done Checking

Why is the last link is printed on a single line and others on two?

E_net4
  • 27,810
  • 13
  • 101
  • 139
JustAnass
  • 11
  • 2

3 Answers3

2

This is because .readlines() will include the new line (\n) character at the end of each line in the file. Notice how only the last URL worked as you expected? This is because the last line of the file did not end in a new line character (Enter) \n

This stack overflow answer discusses a suitable alternative.

codes = NitroCode.read().splitlines()

Additionally, I recommend you use with open("NitroCode.txt") as nitro_codes: instead of NitroCode = open("NitroCode.txt") so that the file will be closed for you automatically upon exit/error.

Henry George
  • 504
  • 6
  • 19
1

It seems like Codes[x] contains a newline character for all values of x except the last one.

To remove any newline characters at the end you can do Codes[x].rstrip('\n')

the.real.gruycho
  • 608
  • 3
  • 17
0

It seems your Codes[x] is read from file with \n new line character in the end, so if you want to prevent that you should strip your Codes[x] value before concatenate:

"https://discordapp.com/api/v6/entitlements/gift-codes/" + Codes[x].strip() + "?with_application=false&with_subscription_plan=true"
godot
  • 3,422
  • 6
  • 25
  • 42