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

2024-06-26 10:18:38 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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")

如何使变量与字符串兼容


Tags: 文件字符串用户txtcloseinput错误create
2条回答

试着做

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

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

相反。或者您只是尝试在open函数上使用模运算符%

用于格式化字符串should take a string ^{} as a first argument%运算符,但是您传递的是从open(...)返回的对象。可以改用此表达式:

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

或者,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;除非万不得已,请不要用它

相关问题 更多 >