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)) |
您正在尝试对
1 | None % <tuple-type> |
号
没有任何意义,并且不是受支持的操作,而对于字符串
@保罗鲁尼在他的答案中解释了你的代码的问题。
执行字符串格式化的首选方法是使用
1 | target.write("{}, {}, {}".format(line1, line2, line3)) |
或者可以使用
1 | target.write(', '.join((line1, line2, line3))) |
。
或者在python 2中使用python 3
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)) |
。
注意,我使用
更多信息:使用"open()"vs"with open()"读取文件