简体   繁体   中英

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

Tried combining target.write into a single line with formatters and am now receiving an error:

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")

Now:

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

same error when using:

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

Full file below:

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()

You meant to write

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

You are attempting a modulus operation on the return value of target.write and a tuple. target.write will be returning None so

None % <tuple-type>

makes no sense and is not a supported operation, whereas for a string % has an overloaded meaning for formatting the string.

@Paul Rooney explains the problem with your code in his answer .

The preferred method of performing string formatting is to use str.format() :

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

Or you could use str.join() to add the separator:

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

Or you even use the Python 3 print function in Python 2:

from __future__ import print_function

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

Life is easy:

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

The parameter inside write() function must be a string, and you can concatenate 2 strings by using the "+" operator.

Notice that I use with open(...) as f to open a file. The reason is with with open() , you don't need to close the file by yourself, it will automatically close when you reach out the with open() block.

More info: File read using "open()" vs "with open()"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM