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

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

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

1
2
3
4
5
6
7
8
9
10
11
TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'

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

现在:

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

使用时出现相同错误:

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

完整文件如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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()


你本来想写的

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

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

1
None % <tuple-type>

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


@保罗鲁尼在他的答案中解释了你的代码的问题。

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

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

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

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

或者在python 2中使用python 3 print函数:

1
2
3
from __future__ import print_function

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


生活很容易:

1
2
3
4
5
6
>>> with open('output.txt', 'w') as f:
...     line1 = 'asdasdasd'
...     line2 = 'sfbdfbdfgdfg'
...     f.write(str(x) + '
'
)
...     f.write(str(y))

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

注意,我使用with open(...) as f打开一个文件。原因是由于with open(),您不需要自己关闭文件,当您到达with open()块时,它会自动关闭。

更多信息:使用"open()"vs"with open()"读取文件