Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if writing to a file fails in Python

Tags:

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()
like image 897
gyula Avatar asked Jul 30 '15 18:07

gyula


1 Answers

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.

like image 68
Will Avatar answered Oct 12 '22 12:10

Will