Program stops working when the list of strings is swapped for a text file

Viewed 47

My program filters through a list of usernames and checks their availability on twitter. In testing I used a list that I entered manually into the code. However, once it was working I swapped them out for a txt file. Only to notice that actually it was no longer checking successfully for the first 4 names in the text file but was working for the last one.

I've printed the json output on the failed 4 tests and it was "Only use letters, numbers and '_'"

available = open("Available-Twitter.txt", "a")

with open ("accounts.txt", "r") as usernames:
   for username in usernames:
       r = requests.get("https://twitter.com/users/username_available?username={}".format(username))
       print (r.json()['msg'])
       print ('       ')

       if "!" in (r.json()['msg']):
          print(Fore.GREEN + "Account available - {}".format(username))
          available.write(username+"\n")
       else:
          print(Fore.RED + "Account is unavailable - {}".format(username)) 
1 Answers

The file generator produces lines that end with a newline character. You should strip it if you don't need it:

with open ("accounts.txt", "r") as usernames:
    for username in usernames:
        username = username.rstrip()
        ...
Related