I'm trying to find a more effective way to access variables within for
loops. I felt that my attempt which works is not an effective way to access variables that are within for
loops.
mylist=None
is the variable in which I want to access within the for
loop.
Also, I want to find a way to minimize the lines of my code either using functions or other suggested approaches and etc.
import csv
import os
from var_dump import var_dump
from orderedset import OrderedSet
# if phone or websites dont appear on spreadsheet change the row indexs
fil = 'newfiles/output8.csv'
with open(fil) as csvfile:
readCSV = csv.reader(csvfile, delimiter=",")
websites = OrderedSet()
phonenumbers = OrderedSet()
emails = OrderedSet()
locations = list()
mylist = None
data = ["electric", "electricians"]
# remove urls that have these strings, only works with the first string
# but not second one.
remo = ["listings", "nationwide", "/mip", "car", "/locations", "/YB", "?utm_source", "/locallocksmithnearby",
"key.me", "find-locksmiths-near-me", "premium-locksmiths", "locksmithnearyou24hrs"]
for row in readCSV:
website = row[1].strip('[]\'')
email = row[0].lower().strip('[]\'')
phonenumber = row[2]
location = row[3]
if location:
if website not in websites:
if phonenumber not in phonenumbers:
if email not in emails:
for x in data:
if x in website:
for r in remo:
if all(r not in website for r in remo):
if phonenumber not in phonenumbers:
if email not in emails:
websites.add(website)
phonenumbers.add(phonenumber)
emails.add(email)
locations.append(location)
mylist = zip(emails, websites, phonenumbers, locations)
if mylist is not None:
number = 0
while os.path.exists('newfiles/newoutput%s.csv' % number):
number += 1
with open('newfiles/newoutput%s.csv' % number, 'w') as csvfile:
writer = csv.writer(
csvfile, delimiter=",")
writer.writerow(
['Email', 'Website', 'Phone Number', 'Location'])
# var_dump(mylist)
for i in mylist:
writer.writerow(list(i))