Issue with conditional statement on external python file - python

I created this script that could be used as a login, and then created an external text file that has the data 1234 in it, this is attempting to compare the data from the file, but outputs that the two values are different, even though they are the same. Thanks In advance to any help you can give me, the code I used is below:
getUsrName = input("Enter username: ")
file = open("documents/pytho/login/cdat.txt", "r")
lines = file.readlines()
recievedUsrName = lines[1]
file.close()
print(getUsrName)
print(recievedUsrName)
if recievedUsrName == getUsrName:
print("hello")
elif getUsrName != recievedUsrName:
print("bye")
else:

Try it like:
if recievedUsrName.strip() == getUsrName:
...
It must be the trailing newline.

Related

For loop only reads the last line of the text file

I have a simple login program where I need user to input the correct details to proceed
,This is my code:
email_l = []
pass_l = []
f = open("lab6.txt", "r")
content = f.readlines()
print(content)
for line in content:
s = line.rstrip()
name,email,password,cn,dob,citi,emergency,creditcardnum,creditcardexp,points = s.split(",")
email_l = email
pass_l = password
usergmail = input("enter gmail:")
if usergmail in email_l:
passcode = input("enter password:")
if passcode in pass_l:
print("Login successful! Welcome",name)
display_user()
else:
print("Wrong Password!")
else:
print("wrong gmail")
and this is what contained in the text file
JunYing,jy654#gmail.com,654321,0125489875,12/05/2001,Malaysian,0175987865,2546 4587 5895 5423,21/28,762
john,ok#gmail.com,123456,0165784399,17/7/2003,Malaysian,0124758995,5874 4585 4569 4214,09/25,547
Pepe,tsy#gmail.com,123598,02654898,8/02/2011,American,02165897,5896 4578 5215 4512,07/25,541
I found out it only reads the last line of the file but I'm using a for loop shouldn't it be reading every line in the file?
How can I make it to read every line in the file and make every email that entered into the input is matched with the file.
Due to some rules, only Array can be utilized in the assignment so I can only use array
You should use email_l.append(email) instead of just over writing it since it is a Python List.
Your list variables "email_l" and "pass_l" are overwritten in each loop iteration.
you have to use:
email_l.append(email)
pass_l.append(password)
in order for your code to work.
refer to python data structures documentation to learn more
https://docs.python.org/3/tutorial/datastructures.html
Take care "display_user()" function is not defined in your communicated code. This will raise undefined function errors.

Python code isnt printing contents of txt?

elif menuOption == "2":
with open("Hotel.txt", "a+") as file:
print (file.read())
Ive tried many different ways but my python file just refuses to print the txt contents. It is writing to the file but option 2 wont read it.
if menuOption == "1":
print("Please Type Your Guests Name.")
data1 = (input() + "\n")
for i in range (2,1000):
file = open("hotel.txt", "a")
file.write(data1)
print("Please Write your Guests Room")
data2 = (input("\n") + "\n")
file.write(data2)
data3 = random.randint(1, 999999)
file.write(str (data3))
print("Guest Added - Enjoy Your Stay.")
print("Guest Name is:", data1)
print("Guest Room Number Is:", data2)
print("Your Key Code Is:", data3)
I want all the above information to be added to a TXT. (That works) and then be able to read it also. which won't work.
Why and how can I fix?
You have to use r instead of a+ to read from file:
with open("Hotel.txt", "r") as file:
You are using a+ mode which is meant for appending to the file, you need to use r for reading.
Secondly I notice this
for i in range (2,1000):
file = open("hotel.txt", "a")
You are opening a new file handler for every iteration of the loop. Please open the file just once and then do whatever operations you need to like below.
with open("hotel.txt", "a") as fh:
do your processing here...
This has the added advantage automatically closing the file handler for you, otherwise you need to close the file handler yourself by using fh.close() which you are not doing in your code.
Also a slight variation to how you are using input, you don't need to print the message explicitly, you can do this with input like this.
name = input("Enter your name: ")

How do I make this more efficient matching input from file within a given range

I have created a username and password program using GUI and I wanted to ensure that if the user enters any of the correct usernames or any of the correct passwords from 2 different files then display 'you have accessed something.' However, I am not sure how to do this, Thank you. It will not work, currently. This is a section of my program:
def reveal(self):
file=open('username.txt','r')
data1=file.readlines()
file.close
file1=open('username.txt','r')
data2=file1.readlines()
file1.close
content2=self.username.get()
content=self.password.get()
if content2==(data1[0,3].replace("\n","")) and content==(data2[0,3].replace("\n","")):
message='You have access to something special.'
else:
message='Access denied.'
self.text.delete(0.0,END)
self.text.insert(0.0,message)
I also tried this, however it still does not work:
def reveal(self):
import itertools
file1=open('username.txt','r')
data1=file1.readlines()
file1.close
file=open('password.txt','r')
data2=file.readlines()
file.close
content2=self.username.get()
content=self.password.get()
with open(username, "r") as file1 , open(password, "r") as file :
if content2 ==itertools.islice(file1,0, 3) and content==itertools.islice(file,0, 3):
message='you have access to something'
else:
message='Access denied.'
I want this program to be able to use multiple usernames and passwords from each of the files, whilst ensuring that only data[0] from the username file matches up with data2[0] from the password file.
Latest version:
def reveal(self):
file=open('username1.txt','r')
data1 =file.read()
file.close()
file1=open('password1.txt','r')
data2 =file1.read()
file1.close()
content2=self.username.get()
content=self.password.get()
data1 = data1.split("\n")
data2 = data2.split("\n")
for i in range(len(data1)):
if data1[i] == content2 and data2[i] == content:
message = 'You have access to something special.'
break
else:
message='Access denied.'
self.text.delete(0.0,END)
self.text.insert(0.0,message)
I'm afraid I don't understand what you're trying to achieve with
data1[0,3].replace("\n","")
and
(data2[0,3].replace("\n","")
If I understand you correctly, there are multiple passwords and usernames in each of their files, and any password can be used with any username?
If so, then you want to do this:
if content2 in data1.split("\n") and content in data2.split("\n"):
message = "You have access to something special."
Note you will need to change file1.readlines() and file.readlines() to file1.read() and file.read() for this to work, or simply take the \n off the end of each line with something like:
data1 = [i[:-1] for i in file.readlines()]
and
data2 = [i[:-1] for i in file1.readlines()]
EDIT:
In order to make it so the first must match the first etc. you can do this:
data1 = data1.split("\n")
data2 = data2.split("\n")
for i in range(len(data1)):
if data1[i] == content2 and data2[i] == content:
message = "You have access to something special."
break

Python name to/from file

I want the text to display the users name if they have entered it before. I have this working in c++ but wanted to practice python. the output will continue to do the "else" statement. I have tried having the if statement search for a string such as "noname" or "empty" and it would still do the else statement.
fr = open('sample.txt','r')
name = fr.read()
fr.close()
if name is None:
fw = open('sample.txt','w')
stuff = raw_input("enter name:")
fw.write(stuff)
fw.close()
else:
print(name)
If you have a blank file without any data in it, f.read() doesn't return None, it returns an empty string.
So rather than do if name is None you could write if name == '' or, to be certain, if name in (None, '').
You might also want to make sure you add a newline character when you write the names to your file, so you should do:
f.write(name + '\n')
for example.
Edit: As Cat Plus Plus mentioned, you can just do if name:, because both None and an empty string will evaluate to False. I just thought it was less clear for this particular question.
Use with to open files, it closes them automtically:
with open('sample.txt','a+') as names: # if file does not exist, "a" will create it
lines = names.read()
if lines: # if file has data
print("Hello {}".format(lines))
else: # else file is empty, ask for name and write name to file
name = raw_input("enter name:")
names.write(name)
To check if the name exists before writing:
with open('sample.txt','a+') as names:
lines = names.read()
name = raw_input("enter name:")
if name in lines:
print("Hello {}".format(name))
else:
names.write(name)

write in capital letters?

i have the next code:
bestand = open("6_frame.txt", "r")
seq = bestand.readlines()
#to make a list
for line in seq:
alle = line
while True:
if alle.isupper():
break
else:
print ("try again ")
with this code i want to make sure that someone , who write a sequence in the file, write this sequence in capital letters, and want to except the other errors: but he want do what i want.
can somebody help me ??
I think you are saying you want to ensure the entire file is in upper-case. If that's what you are looking for, this will do the trick:
if all(x.isupper() for x in open("6_frame.txt", "r")):
print("entire file is upper-case.")
else:
print("try again!")
This will test the file, line-at-a-time, for all upper-case characters. If it finds a line that is not, it will return false, otherwise if all lines are upper-case, return true (and print "entire file is upper-case").
Update (File watching edition)
It looks like you want to keep checking the file until it's all uppercase. Here's a fairly ineffecient way to do it (you could add modtime checks, or use inotify to make it better):
from time import sleep
while True:
lines = open("6_frame.txt", "r")
if all((x.isupper() or x.isspace()) for x in lines):
print("entire file is upper-case.")
break # We're done watching file, exit loop
else:
print("try again!")
sleep(1) # Wait for user to correct file
Also, you may get exceptions (I'm not sure) if the person is mid-save when your script checks the file again, so you may need to add some exception catching around the all line. Either way... Hope this helps!
My abc.txt content is aBC, so not all uppercase:
fd = open('abc.txt','r')
seq = fd.readlines()
for line in seq:
if line.isupper():
print('all capital')
else:
print('try again')
therefore my output = try again
if my abc.txt content is ABC my output is all capital
Determine whether all cased characters in the file are uppercase, retry if not:
import time
from hashlib import md5
hprev = None
while True:
with open("6_frame.txt") as f:
text = f.read()
if text.isupper():
print('all capital')
break
else:
h = md5(text).hexdigest()
if h != hprev: # print message if the file changed
print('try again')
hprev = h
time.sleep(1) # wait for the file to change

Categories

Resources