0

I am trying to ask the user what they want to name a file that is about to be created on my desktop. When I try to add the variable to the string, it gives me this error:

appendFile = open('%s.txt', 'a') % cusername
TypeError: unsupported operand type(s) for %: '_io.TextIOWrapper' and 'str'

Here is my program:

def CNA():
    cusername = input("Create username\n>>")
    filehandler = open("C:/Users/CJ Peine/Desktop/%s.txt", "w") % cusername
    filehandler.close()
    cpassword = input("Create password\n>>")
    appendFile = open('%s.txt', 'a') % cusername
    appendFile.write(cpassword)
    appendFile.close()
    print ("Account Created")

How do I make the variable compatible to the string?

CJ Peine
  • 67
  • 4

2 Answers2

1

Try doing

cusername = input("Create username\n>>")

filehandler = open("C:/Users/CJ Peine/Desktop/" + cusername + ".txt", "w")

instead. Or you're just trying use modulus operator % on open function.

Nae
  • 14,209
  • 7
  • 52
  • 79
0

The % operator for formatting strings should take a string str as a first argument but instead you're passing the object returned from open(...). You can use this expression instead:

open("C:/Users/CJ Peine/Desktop/%s.txt" % cusername, "w")

Alternatively, Python 3 supports using the str.format(str) method ("C:/Users/CJ Peine/Desktop/{}.txt".format(cusername)), which IMHO is much more readable, and Python 3 is much better than Python 2 anyway. Python 2 has been out of active development for ages and is scheduled to no longer be supported; please don't use it unless you absolutely have to.

errantlinguist
  • 3,658
  • 4
  • 18
  • 41