Blog Real Life Examples

How to create a website blocker using Python

In this post we are going to write a Python code that blocks certain website which distract us from our goals.


What we are going to in this program is that we will pass the link of websites which you think is distracting and the time that you are working on your computer and program will block those website.

Program Architecture:

Every system have host file whether it is Mac, Windows or Linux.
Host file in Mac and Linux :


Host file in Windows:


Working of host file: Host is an operating system file which maps hostnames to IP addresses. In this program we will be mapping hostnames of websites to our localhost address. Using python file handling manipulation we will write the hostname in hosts.txt and remove the lines after your working hours.

Host file in windows looks like this

# Run this script as root

import time
from datetime import datetime as dt

# change hosts path according to your OS
hosts_path = "/etc/hosts"
# localhost's IP
redirect = ""

# websites That you want to block
website_list =

while True:

	# time of your work
	if dt(,,,8)
	< < dt(,,,16):
		print("Working hours...")
		with open(hosts_path, 'r+') as file:
			content =
			for website in website_list:
				if website in content:
					# mapping hostnames to your localhost IP address
					file.write(redirect + " " + website + "\n")
		with open(hosts_path, 'r+') as file:
			for line in content:
				if not any(website in line for website in website_list):

			# removing hostnmes from host file

		print("Fun hours...")

Special Note

Run your Python IDE as administrator as you(Current User) might not have permission to access to hosts file.

For more Python related blogs Visit Us Geekycodes . Follow us on Instagram.

If you’re a college student and have skills in programming languages, Want to earn through blogging? Mail us at

Leave a Reply

%d bloggers like this: