Python 为什么这种类型的变量与字符串不兼容?

Python 为什么这种类型的变量与字符串不兼容?,python,Python,我试图询问用户,他们想为即将在我的桌面上创建的文件命名什么。当我尝试将变量添加到字符串时,会出现以下错误: appendFile = open('%s.txt', 'a') % cusername TypeError: unsupported operand type(s) for %: '_io.TextIOWrapper' and 'str' 这是我的节目: def CNA(): cusername = input("Create username\n>>")

我试图询问用户,他们想为即将在我的桌面上创建的文件命名什么。当我尝试将变量添加到字符串时,会出现以下错误:

appendFile = open('%s.txt', 'a') % cusername
TypeError: unsupported operand type(s) for %: '_io.TextIOWrapper' and 'str'
这是我的节目:

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")
如何使变量与字符串兼容?

尝试执行以下操作

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

filehandler = open("C:/Users/CJ Peine/Desktop/" + cusername + ".txt", "w")
相反。或者您只是尝试在open函数上使用模数运算符%。

用于格式化字符串的%运算符,但您传递的是从open返回的对象。。。。您可以改为使用此表达式:

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

或者,哪个IMHO更具可读性,而且不管怎样,Python 3比Python 2要好得多;除非必须使用,否则请不要使用它。

%cusername必须与“%s.txt”一起使用,而不是与openopen一起使用。。。应该返回一个文件处理程序。文件\u处理程序%cusername的含义是什么?当我这样做时,桌面上会显示一个文本文件%cusername,而不是我输入的变量。@CJPeine:您指的是什么变量?C:/Users/CJ Peine/Desktop/%s.txt%cusername。。。也应该有效。