gyula
gyula

Reputation: 257

How to check if writing to a file fails in Python

how can I print out a message if the action was successful?

For example: I want to write a string to a file, and if everything was ok, it should print out an "ok" message. It is possible with an easy way?

Edit:

for root, dirs, files in os.walk('/Users'):
    for f in files:
        fullpath = os.path.join(root, f)
        if os.path.splitext(fullpath)[1] == '.'+ext:
            outfile = open('log.txt', 'w')
            outfile.write(fullpath)
            outfile.close()

Upvotes: 5

Views: 6854

Answers (1)

Will
Will

Reputation: 4469

In short: python will tell you if there's an error. Otherwise, it is safe to assume everything is working (provided your code is correct)

For example:

a = "some string"
print "Variable set! a = ", a

would verify that the line a = "some string" executed without error.

You could make this more explicit like so:

try:
  a = "some string"
  print "Success!"
except:
  print "Error detected!"

But this is bad practice. It is unnecessarily verbose, and the exception will print a more useful error message anyway.

Upvotes: 5

Related Questions