Pergunta

import os

def closed(x):
        if f.closed == True:
                return "closed"
        else:
                return "open"

f = open("test.txt", "ab")
print "Name of the file: ", f.name
print "we just opened the file so the file is: ", closed(f)
f.write("I am writing now to the file %s \n") % (f.name)
f.close()
print "now we typed f.close(), so it is: ", closed(f)

It gives me error, and prints out to test.txt the %s and doesn't understand %s? why?

Traceback (most recent call last): File "attempt1.py", line 12, in f.write("I am writing now to the file %s \n") % (f.name) TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'

I want it to write "I am writing now to the file test.txt" using the %s

Foi útil?

Solução

You're not formatting the string correctly, fix this line:

f.write("I am writing now to the file %s \n" % f.name)

On your code, you closed the parenthesis leaving the string unformatted and with a SyntaxError since % (f.name) is not valid Python.

By the way, that kind of formatting is been improved with str.format(). Something like this:

f.write("I am writing now to the file {} \n".format(f.name))

Outras dicas

Your % is outside of print try

f.write("I am writing now to the file %s \n" % f.name)

To expand on Paulo Bu's answer, file handling has also improved. I'm talking about Context Managers. They automatically call .close() on your managed object for you.

Here's how your snippet would look like:

import os

with open("test.txt", "a") as f:
    print("Name of the file:", f.name)
    f.write("I am writing now to the file {} \n".format(f.name))

Furthermore, you'll notice I removed the "b" from open()'s mode parameter. It looks like you're just appending text, not binary data, so that "b" doesn't make sense. Have a looksee here (python's built-in open function docs) at the flags you can pass to mode and what they mean.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top