Mcrey Fonacier
Mcrey Fonacier

Reputation: 157

for loop error in python

Why do i get an error when i go "if not any(line in website_list)" and why do i need the website variable? huhuhu help

When i am doing "if not any(line in website_list)" an error pops-up in that line, why do i need another variable 'website' in order to execute this? by the way i am a beginner.

I am creating a blocker app during working time.

import time
import numpy as np
from datetime import datetime as dt

hosts_temp = "hosts" #temporary
hosts_path = r"C:\Windows\System32\drivers\etc\hosts"
redirect = "127.0.0.1"
website_list = np.array(["www.facebook.com", "facebook.com", "fb.com"])

while True:

    if dt(dt.now().year, dt.now().month, dt.now().day, 8) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day, 9):
        print("Working hours")
        with open(hosts_temp, "r+") as file:
            content = file.read()
            for debsite in website_list:
                if debsite in content:
                    pass 
                else:
                    file.write(redirect + " " + debsite + '\n')

    else:
        with open(hosts_temp, 'r+') as file:
            content = np.array(file.readlines())
            file.seek(0)
            for line in content:
                if not any(website in line for website in website_list): # I CAN'T UNDERSTAND THIS LINE
                # ^ cant understand this 
                    file.write(line)
            file.truncate()
        print("Fun hours")
    time.sleep(3)

Upvotes: 0

Views: 59

Answers (1)

awesoon
awesoon

Reputation: 33651

if not any(website in line for website in website_list)

This line means "if website_list does not contain any website such that line contains website"

any function accepts an iterable and checks that there is at least one element has truth value.

website in line for website in website_list is a generator for True / False series where True with index idx means that the line contains website on the index idx

if not any(line in website_list) does not work because line in website_list returns True or False. It also has different meaning, line in website_list means "website_list contains at least one element which is equal to line"

Upvotes: 1

Related Questions