-1

Using python, I am trying to edit the hosts file.

with open('C:\Windows\System32\drivers\etc\hosts', 'r+') as file:
    data = file.readlines()
    data[70] = '127.0.0.1 web.alanmrsa.com'
    file.writelines(data)
    print('done')

When I run this file, it gives me the following error:

PermissionError: [Errno 13] in python

Alex Kulinkovich
  • 4,408
  • 15
  • 46
  • 50
Alan Ma
  • 19
  • 2
  • 1
    Please include the complete error message. It is impossible to tell which statement generated it. – DYZ Sep 16 '18 at 02:26

1 Answers1

1

C:\Windows\System32\drivers\etc\hosts is writable only by Administrator. You should run your script as Administrator instead.

Also note that you should do a file.seek(0) after data = file.readlines() so that you can overwrite the original content, and also do a file.truncate() after file.writelines(data) so that there would be no leftover characters from the original content in case your replacement string is shorter than the content of the original 71th line.

blhsing
  • 91,368
  • 6
  • 71
  • 106
  • How would I go about running as administrator? I’ve tried some of the solutions on stack overflow but they just result in my python exiting – Alan Ma Sep 16 '18 at 04:10
  • 1
    Try running `cmd` as Administrator first, and then run your script from the command line session. – blhsing Sep 16 '18 at 04:16
  • It still gives me the following error with open('C:\Windows\System32\drivers\etc\hosts', 'r+') as file: PermissionError: [Errno 13] Permission denied: 'C:\\Windows\\System32\\drivers\\etc\\hosts' – Alan Ma Sep 17 '18 at 02:47
  • Try running the script with `runas /user:Administrator path_to_script` in command line. – blhsing Sep 17 '18 at 03:55