Python - Writing to the hosts file

How can I add a new line to the hosts file (located C:/Windows/System32/drivers/etc/hosts)? This file is protected and requires administrator privileges to be modified - can Python detect if it cannot edit the file and display an error?

OS: Windows 7
Language: Python
Who is Participating?
HonorGodSoftware EngineerCommented:
As Superdave said...
>>> import sys
>>> try :
...   fh = open( '/etc/hosts', 'w+' );
...   fh.close();
... except :
...   t, v = sys.exc_info()[ :2 ]
...   print 'Exception  type: %s' % str( t );
...   print 'Exception value: %s' % str( v );
Exception  type: exceptions.IOError
Exception value: [Errno 13] Permission denied: '/etc/hosts'

Open in new window

Catch the IOError exception when you try to open it.
HonorGodSoftware EngineerCommented:
Thanks for the grade and points.

Good luck & have a great day.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.