我正在尝试询问用户他们想要命名一个即将在我的桌面上创建的文件。当我尝试将变量添加到字符串时,它会给我这个错误:
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")
如何使变量与字符串兼容?
答案 0 :(得分:1)
尝试
cusername = input("Create username\n>>")
filehandler = open("C:/Users/CJ Peine/Desktop/" + cusername + ".txt", "w")
代替。或者您只是在%
函数上尝试使用模数运算符open
。
答案 1 :(得分:0)
%
运算符用于格式化字符串should take a string str
as a first argument,而是您传递从open(...)
返回的对象。您可以改为使用此表达式:
open("C:/Users/CJ Peine/Desktop/%s.txt" % cusername, "w")
或者,Python 3 supports using the str.format(str)
method ("C:/Users/CJ Peine/Desktop/{}.txt".format(cusername)
),其中恕我直言更易读,而且Python 3比Python 2好得多。 Python 2 has been out of active development for ages and is scheduled to no longer be supported;除非你绝对必须,否则请不要使用它。