Python - TypeError:%不支持的操作数类型:'NoneType'和'tuple'

时间:2017-02-06 02:13:45

标签: python python-2.7 tuples formatter nonetype

尝试将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()

3 个答案:

答案 0 :(得分:2)

你打算写

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

您正在尝试对target.write和元组的返回值进行模运算。 target.write将返回None所以

None % <tuple-type>

没有意义,也不是受支持的操作,而对于字符串%来说,格式化字符串的含义过重。

答案 1 :(得分:1)

@Paul Rooney在他的answer中解释了您的代码问题。

执行字符串格式化的首选方法是使用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='')

答案 2 :(得分:0)

生活很简单:

>>> 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()区块时它会自动关闭。

更多信息:File read using "open()" vs "with open()"