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?

4
  • 2
    The % cusername needs to be with '%s.txt' and not with open() Commented Oct 24, 2017 at 3:56
  • 1
    open(...) supposed to return a file-handler. what's the meaning of file_handler % cusername ? Commented Oct 24, 2017 at 3:59
  • when i do that a text file shows up on my desktop with % cusername instead of the variable i put in. Commented Oct 24, 2017 at 4:01
  • 1
    @CJPeine: what variable you are referring to? ("C:/Users/CJ Peine/Desktop/%s.txt" % cusername ... should work as well. Commented Oct 24, 2017 at 4:11

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.