Search code examples
pythonpython-2.7tuplesformatternonetype

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

Solution

  • 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.