Python -- TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'

Python -- TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'

尝试将 target.write 与格式化程序组合成一行,但现在收到错误消息:

TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

现在:

target.write("%s, %s, %s") % (line1, line2, line3)

使用时同样的错误:

target.write("%r, %r, %r") % (line1, line2, line3)

完整文件如下:

from sys import argv

script, filename = argv

print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename, 'w')

print "Truncating the file. Goodbye!"
target.truncate()

print "Now I'm going to ask you for three lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "I'm going to write these to the file."

target.write("%s, %s, %s") % (line1, line2, line3)

print "And finally, we close it."
target.close()

你本来想写的

target.write("%s, %s, %s" % (line1, line2, line3))

您正在尝试对 target.write 的 return 值和一个元组进行取模运算。 target.write 将 returning None 所以

None % <tuple-type>

没有任何意义,也不是受支持的操作,而对于字符串,% 对格式化字符串具有重载意义。

@Paul Rooney 在他的 .

中解释了您的代码存在的问题

执行字符串格式化的首选方法是使用 str.format():

target.write("{}, {}, {}".format(line1, line2, line3))

或者您可以使用 str.join() 添加分隔符:

target.write(', '.join((line1, line2, line3)))

或者你甚至在 Python 2:

中使用 Python 3 print 函数
from __future__ import print_function

print(line1, line2, line3, sep=', ', file=target, end='')

生活很简单:

>>> with open('output.txt', 'w') as f:
...     line1 = 'asdasdasd'
...     line2 = 'sfbdfbdfgdfg'
...     f.write(str(x) + '\n')
...     f.write(str(y))

write()函数中的参数必须是字符串,可以使用“+”运算符连接2个字符串。

请注意,我使用 with open(...) as f 打开文件。原因是with open(),你不需要自己关闭文件,当你伸出with open()块时它会自动关闭。

更多信息: