3

I would like to add a line in my Windows hosts file via Python with this code:

fh = open("C:\Windows\System32\drivers\etc\hello.txt", "w")
fh.write("new line")
fh.close()

But I get this error:

PermissionError: [Errno 13] Permission denied: 'C:\\Windows\\System32\\drivers\\etc\\hello.txt'

It doesn't work even if my antivirus is disabled.

I don't know how to write a file as an administrator on a Windows machine.

halflings
  • 1,540
  • 1
  • 13
  • 34
jmercier
  • 564
  • 2
  • 7
  • 17
  • 1
    First, if you want to *add* a line, you should use `fh = open("C:\..", "a")`. With `"w"` you truncate the file. Next to have admin permission on a windows machine, you must ... start the python interpretor as administrator ! – Serge Ballesta Apr 21 '15 at 11:15

3 Answers3

2

What you need to do is run your Python script with elevated privileges.

Refer to this question and this one to do so.

Community
  • 1
  • 1
halflings
  • 1,540
  • 1
  • 13
  • 34
2

You need to run Python as administrator, then it can write files in normally protected directories.

A command like

runas.exe /user:administrator "C:\Python34\python.exe myscript.py"

(edited for your actual Python installation and script paths) should work. You'll still need to provide a password.

Also, you should be using raw strings for Windows pathnames - you were just lucky that none of the backslashes preceded an escapable character:

fh = open(r"C:\Windows\System32\drivers\etc\hello.txt", "a") # add, not overwrite
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
-2

This question is for Windows, but i thought i'd give an answer for Linux since future readers might be on Linux.

You can use sudo, given that you have the sufficient permissions in the /etc/sudoers file.

sudo python myscript.py

You will be prompted to enter your password.

Stian OK
  • 658
  • 6
  • 14