我试着问用户他们想给一个即将在我的桌面上创建的文件取什么名字。当我尝试将变量添加到字符串时,会出现以下错误:
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")
如何使变量与字符串兼容
试着做
相反。或者您只是尝试在
open
函数上使用模运算符%
用于格式化字符串should take a string ^{} as a first argument 的
%
运算符,但是您传递的是从open(...)
返回的对象。可以改用此表达式:或者,Python 3 supports using the ^{} method (^{}) ,IMHO可读性更好,而python3比python2好得多Python 2 has been out of active development for ages and is scheduled to no longer be supported;除非万不得已,请不要用它
相关问题 更多 >
编程相关推荐