I have a .txt file where names and addresses appear in the following format:
Sam, 35 Marly Road
...
...
I want to be able to search Sam and for 35 Marly Road to come up.
Here is the code I have so far:
name = input("Please insert your required Client's name: ")
if name in open('clientAddress.txt').read():
print ("Client Found")`
This checks if the ID inputted is available in the file, but it doesn't print the address. How do I change it, so it finds the name and prints the address?
As a quick solution - see below
username = input()
with open('clientRecords.txt', 'r') as clientsfile:
for line in clientsfile.readline():
if line.startswith("%s, " % username):
print("Cient %s found: %s" % (username, line[len(username) + 2:]))
break
Simple solution
username = input()
with open('clientRecords.txt', 'r') as clientsfile:
for line in clientsfile:
if line.startswith("%s, " % username):
print("Client %s found: %s" % (username, line.split(",")[1]))
break
For loop iterates through file lines and when we found line starts with desired client name we print address and break loop.
Related
I am having problem in my project
just see my code
import subprocess
a=input("WANT SPECIFIC PASSWORD OR OF ALL if all type all if specific type wifi name")
if(a=="all"):
data=subprocess.check_output(['netsh','wlan','show','profiles']).decode('utf-8').split('\n')
wifis=[line.split(':')[1][1:-1] for line in data if"All User Profile"in line]
for wifi in wifis:
resilt=subprocess.check_output(['netsh','wlan','show','profile',wifi,'key=clear']).decode('utf-8').split('\n')
resilt=[line.split(':')[1][1:-1]for line in resilt if "Key Content" in line]
try:
print('Name',':',wifi,'Password:'+resilt[0])
except IndexError:
print('Name',':',wifi,'Password : Cannot be read!')
else:
data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles']).decode('utf-8').split('\n')
wifis = [line.split(':')[1][1:-1] for line in data if "All User Profile" in line]
for wifi in wifis:
resilt = subprocess.check_output(['netsh', 'wlan', 'show', 'profile', wifi, 'key=clear']).decode('utf-8').split(
'\n')
resilt = [line.split(':')[1][1:-1] for line in resilt if "Key Content" in line]
if (a in wifi):
# print('Name :', fg, "\n"'Password:' + resilt[0])
try:
print('Name :',a,"\n"'Password:' + resilt[0])
except IndexError:
print('Name', ':', a, 'Password zz: There is no password!')
elif (a not in wifi):
print("There is no wifi name",a,"in your system")
Here my problem is that when i give input all to get all wifi's password which is in my pc then it is working fine but when I am giving specific wifi name to get it's password then it is giving but.Just see the photo
Here it is showing the password but it is also showing "There is no wifi name Priyanshu in your system"here I am giving the correct name.I just only want that it will only show the name and password not any other things and the statement "There is no wifi........"it is showing it 6 times not one time.I just only want the name and password
And when I am giving the wrong password
then it is showing the statement 6 times not just only one Time.I want only one time.
I am just confused what I have to do.
The code is correct but this is the customised version you are asking for
for wifi in wifis:
resilt = subprocess.check_output(['netsh', 'wlan', 'show', 'profile', wifi, 'key=clear']).decode('utf-8').split(
'\n')
resilt = [line.split(':')[1][1:-1] for line in resilt if "Key Content" in line]
if (a in wifi):
# print('Name :', fg, "\n"'Password:' + resilt[0])
try:
print('Name :',a,"\n"'Password:' + resilt[0])
except IndexError:
print('Name', ':', a, 'Password zz: There is no password!')
break
else :
print("There is no wifi name",a,"in your system")
Explanation:
If the wifi with desired name is found the code within if block executes. It also executes the break command which terminates the loop. The last else statement only executes if the for loop terminates after it's complete execution. So, if the desired wifi is not found it will execute. But, if the desired wifi is found then the break command will skip the else part.
You have a for loop, and inside it, you have if and elif statements. So it found it will print it and if not, it will print the message, (as you have in 1st screenshot of output).
If there is no such wifi, still it will print it.
I think there is no problem, script is working as it should.
You can also break of out loop if you find the currect wifi, and better not to print that "no wifi found..."...
i have made that when ever someone reg the txt file is created and named on user username. now im trying to check if username txt file is there in dir or not here is the code i tried .
im unable to check if username txt file is there . i tried many diff way searched google but no luck some i have mentioned as comment. pls help looking
def db():
a = (E1.get(), E2.get(), E3.get(),E4.get(),E5.get())
if "./library/"+E1.get() == os.path.isfile("./library/"+E1.get()):
# if E1.get() == os.path.isfile(E1.get()):
# if E1.get()in os.path.isdir("./library/"):
cur.execute("insert into Booking values(?,?,?,?,?)", a)
con.commit()
cur.execute("select * from Booking")
a = cur.fetchall()
ab = int(E4.get())
cost=100
ac = ab * cost
messagebox.showinfo("Congratulation!!", "Your oreder value is %s" % ac)
print(a)
te.destroy()
os.system("library.py")
else:
print("username invalid")
Try replacing the below line
if "./library/"+E1.get() == os.path.isfile("./library/"+E1.get()):
with
if os.path.isfile("./library/"+E1.get()):
You probably are confused with the return value of os.path.isfile() fn.
I have been working on a script to ingest a file (accounts.txt) which contains email addresses, for which each will then be verified against an API to see if they appear in a data dump. The script appears to work, however there is a bug present whereby once it finds a positive hit, it will disregard any other match...
For example;
If my "accounts.txt" file contains the following entries:
a#a.com
b#b.com
Even though both of those should return results, as soon as the script is run, the match on a#a.com will be found however b#b.com will not return anything.
I cannot seem to figure out why this is happening, ideally I want all of the hits outputted.
FYI, the script is querying 'haveibeenpwned' which is a site that locates email addresses found in credential dumps.
Any help finding my bug would be greatly appreciated. Below is my current script.
#!/usr/bin/env python
import argparse
import json
import requests
import time
breaches_by_date = {}
breaches_by_account = {}
breaches_by_name = {}
class Breach(object):
def __init__(self, e, n, d):
self.email = e
self.name = n
self.date = d
def __repr__(self):
return "%s: %s breached on %s" % (self.email, self.name, self.date)
def accCheck(acc):
global breaches_by_date, breaches_by_account, breaches_by_name
r = requests.get('https://haveibeenpwned.com/api/v2/breachedaccount/%s?truncateResponse=false' % acc)
try:
data = json.loads(r.text)
except ValueError:
print("No breach information for %s" % acc)
return
for i in data:
name, date = (i['Name'], i['BreachDate'])
breach = Breach(acc, name, date)
try: breaches_by_account[acc].append(breach)
except: breaches_by_account[acc] = [breach]
try: breaches_by_name[name].append(breach)
except: breaches_by_name[name] = [breach]
try: breaches_by_date[date].append(breach)
except: breaches_by_date[date] = [breach]
def readFromFile(fname="accounts.txt"):
accounts=[]
with open(fname, "r+") as f:
accounts = [l.strip() for l in f.readlines()]
return accounts
if __name__ == '__main__':
accounts = readFromFile()
for email_addr in accounts:
accCheck(email_addr)
print
print("Breaches by date")
for date, breaches in breaches_by_date.items():
for breach in breaches:
print(breach)
print
print("Breaches by account")
for acc, breaches in breaches_by_account.items():
print(acc)
for breach in breaches:
print("%s breached on %s" % (breach.name, breach.date))
print
print("Breaches by name")
for name, breaches in breaches_by_name.items():
print("%s breached for the following accounts:" % name)
for breach in breaches:
print("%s on %s" % (breach.email, breach.date))
print
I am not 100% sure to know where your problem comes from, but I would opt for a code like:
emails_to_check = open("/path/to/yourfile").read().split("\n")
for email in emails_to_check:
if is_email_blacklisted(email):
do_something()
This is basically a effort to learn mapping for dictionary, basically i have a function which prints the change in a port , the code is as follows :
def comp_ports(self,filename,mapping):
try:
#print "HEYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY"
f = open(filename)
self.prev_report = pickle.load(f) # NmapReport
for s in self.prev_report.hosts:
self.old_port_dict[s.address] = set()
for x in s.get_open_ports():
self.old_port_dict[s.address].add(x)
for s in self.report.hosts:
self.new_port_dict[s.address] = set()
for x in s.get_open_ports():
self.new_port_dict[s.address].add(x)
print "The following Host/ports were available in old scan : !!"
print `self.old_port_dict`
print "--------------------------------------------------------"
print "The following Host/ports have been added in new scan: !!"
print `self.new_port_dict`
##
for h in self.old_port_dict.keys():
self.results_ports_dict[h] = self.new_port_dict[h]- self.old_port_dict[h]
print "Result Change: for",h ,"->",self.results_ports_dict[h]
################### The following code is intensive ###################
print "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
diff_key=[key for key in self.old_port_dict if self.old_port_dict[key]!=self.new_port_dict[key]]
for key in diff_key:
print "For %s, Port changed from %s to %s" %(key,self.old_port_dict[key],self.new_port_dict[key])
The way i call this is via main function,
if __name__ == "__main__":
if len(sys.argv) < 2:
print "Usage:\n\tportwatch.py <configfile> [clean]"
sys.exit(-1)
else:
# Read
config = ConfigParser.ConfigParser()
config.read(sys.argv[1])
if len(sys.argv) > 2:
if sys.argv[2] == "clean":
for f in ['nmap-report-old.pkl','nmap-report.pkl']:
try:
os.remove( config.get('system','scan_directory') + "/" + f )
except Exception as e:
print e
# Configure Scanner
s = Scanner(config)
# Execute Scan and Generate latest report
net_range = gather_public_ip() #config.get('sources','networks') # gather_public_ip()
### r = s.run(','.join([[i[0] for i in v] for v in net_range][0]))
r = s.run(net_range)
data = list(itertools.chain(*net_range))
mapping = {i[0]:[i[1],i[2]] for i in data}
s.save()
report = Report(r)
report.dump_raw(mapping) ## change made for dump to dump_raw
print "Hosts in scan report",report.total_hosts()
# Read in last scan
report.compare(config.get('system','scan_directory') + '/nmap-report-old.pkl' )
print "New Hosts"
report.new_hosts()
# slack.api_token = config.get('notification','slack_key')
notify_slack_new_host(report.new_hosts()) #Notifty Slack for any new added host
# for h in report.result_port_dict.keys():
# notify_slack(report.new_hosts(h))
print "Lost Hosts"
report.lost_hosts()
report.comp_ports(config.get('system','scan_directory') + '/nmap-report-old.pkl',mapping)
The whole code is at http://pastebin.com/iDYBBrEq , can someone please help me at comp_ports where i want to also add the tag and region name as similer to dump_raw.
Please help
Since the IP is your key in the dictionaries old_port_dict, new_port_dict and mapping and in mapping each IP maps to a list with tag at index 0 and region at index 1, the way to access those will be.
for key in diff_key:
print "For %s with tag %s and region %s, Port changed from %s to %s" %(key,mapping[key][0],mapping[key][1],self.old_port_dict[key],self.new_port_dict[key])
So I wrote this code
spec = raw_input("Enter the specimen number: ")
naorimp = raw_input("Native or Implant (N/I)? ")
trial = raw_input("Trial number: ")
typana = raw_input("What do you want to analyze (contact area[CA]/contact pressure[CP])? ")
try :
if typana.lower() == "cp" :
naorimp = naorimp.upper()
TSfilnm = 'pressure'+spec+naorimp.upper()+trial+'.txt'
else :
naorimp = naorimp.upper()
TSfilnm = 'area'+spec+naorimp+trial+'.txt'
TSfile = open(TSfilnm, 'r')
myofilnm = 'accelerometer'+spec+naorim.upper()+trial+'.txt'
print myofilnm
myofile = open(myofilnm, 'r')
except :
print "File could not be found."
print "Please re-run the program."
exit()
print "OK"
I want to open a file based on user's input and several parameters (specimen no., native or implant, trial no., and type of analysis.) The file is already in the same folder as the python file code. But when I run the program I always end up with except statements (File could not be found. Please re-run the program). I have double-checked the real file name and the string inside the TSfilnm variable, and they are the same. However, the TSfile could not be executed.
P.S. The file name in my folder is: pressure3N1.txt, area3N1.txt, accelerometer3N1.txt
You are missing a p in the variable name in this line
myofilnm = 'accelerometer'+spec+naorim.upper()+trial+'.txt'
should be
myofilnm = 'accelerometer'+spec+naorimp.upper()+trial+'.txt'
Also don't use 'except' alone during development, it will only hide errors like in this case. It's better to do something like.
import sys
try:
#Your_code_here
except:
print sys.exc_info()[1]
#Any other code you wanna run