For loop only reads the last line of the text file - python

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.

Related

keep getting IndexError: list index out of rangeIndexError: list index out of range

I'm trying to make the code check if the entered username and password are valid by comparing them to the content of a text file, but I keep getting this IndexError: list index out of range.
The problem is the code was working fine and then for unknown reason it's stopped.
Here is the python code
class Login_Screen(MDScreen):
def log_in(self):
username = self.ids.username.text
password = self.ids.pwd.text
login_btn = self.ids.login_btn
with open(r'D:\Downloads\GP\code\Hamster-App-master\libs\uix\baseclass\userinfo.txt','r') as info_file:
read_file = csv.reader(info_file)
for line in read_file:
if line[0]== username and line[1]== password:
login_btn.disabled = False
break
else:
break
info_file.close()
and the text file only have 2 lines:
ola
123
I tried to use for line in read_file and for row in read_file.
You made a for loop for 2 lines but for each line you ask for two arguments
try to make sure if there is a line
for line in read_file:
if line[0] and line[1]:
if line[0]== username and if line[1]== password:

Creating a search function in a list from a text file

everyone. I have a Python assignment that requires me to do the following:
Download this CSV fileLinks to an external site of female Oscar winners (https://docs.google.com/document/d/1Bq2T4m7FhWVXEJlD_UGti0zrIaoRCxDfRBVPOZq89bI/edit?usp=sharing) and open it into a text editor on your computer
Add a text file to your sandbox project named OscarWinnersFemales.txt
Copy and paste several lines from the original file into your sandbox file. Make sure that you include the header.
Write a Python program that does the following:
Open the file and store the file object in a variable
Read the entire contents line by line into a list and strip away the newline character at the end of each line
Using list slicing, print lines 4 through 7 of your file
Write code that will ask the user for an actress name and then search the list to see if it is in there. If it is it will display the record and if it is not it will display Sorry not found.
Close the file
Below is the code I currently have. I've already completed the first three bullet points but I can't figure out how to implement a search function into the list. Could anyone help clarify it for me? Thanks.
f = open('OscarsWinnersFemales.txt')
f = ([x.strip("\n") for x in f.readlines()])
print(f[3:7])
Here's what I tried already but it just keeps returning failure:
def search_func():
actress = input("Enter an actress name: ")
for x in f:
if actress in f:
print("success")
else:
print("failure")
search_func()
I hate it when people use complicated commands like ([x.strip("\n") for x in f.readlines()]) so ill just use multiple lines but you can do what you like.
f = open("OscarWinnersFemales.txt")
f = f.readlines()
f.close()
data = {} # will list the actors and the data as their values
for i, d in enumerate(data):
f[i] = d.strip("\n")
try:
index, year, age, name, movie = d.split(",")
except ValueError:
index, year, age, name, movie, movie2 = d.split(",")
movie += " and " + movie2
data[name] = f"{index}-> {year}-{age} | {movie}"
print(f[3:7])
def search_actr(name):
if name in data: print(data[name])
else: print("Actress does not exist in database. Remember to use captols and their full name")
I apologize if there are any errors, I decided not to download the file but everything I wrote is based off my knowledge and testing.
I have figured it out
file = open("OscarWinnersFemales.txt","r")
OscarWinnersFemales_List = []
for line in file:
stripped_line = line.strip()
OscarWinnersFemales_List.append(stripped_line)
file.close()
print(OscarWinnersFemales_List[3:7])
print()
actress_line = 0
name = input("Enter An Actress's Name: ")
for line in OscarWinnersFemales_List:
if name in line:
actress_line = line
break
if actress_line == 0:
print("Sorry, not found.")
else:
print()
print(actress_line)

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: ")

Program re-writes over saved file data

So I have this program that I've written in Python 2.7 which takes user input of various employee information and writes it to a file. I put the main block of code into a function, because I want to be able to run it multiple times. The code I currently have is below:
def employeeInformation():
# opens text file data will be stored in
with open('employeeFile.txt', 'w') as dataFile:
# gets user input for employee name
employeeName = raw_input('Employee Name: ')
# checks if the input is a string or not
if not employeeName.isalpha():
print('Invalid data entry')
else:
# if input is string, write data to file
dataFile.write(employeeName + '\n')
# gets user input for employee age
employeeAge = raw_input('Employee Age: ')
if not employeeAge.isdigit():
print('Invalid data entry')
else:
# if input is number, write data to file
dataFile.write(employeeAge + '\n')
# gets user input for employee role
employeeRole = raw_input('Employee Role: ')
if not employeeRole.isalpha():
print('Invalid data entry')
else:
# if input is string, write data to file
dataFile.write(employeeRole + '\n')
employeeSalary = raw_input('Employee Salary: ')
if not employeeSalary.isdigit():
print('Invalid data entry')
else:
# if input is number, write data to file
dataFile.write(employeeSalary + '\n')
dataFile.close()
employeeInformation()
employeeInformation()
employeeInformation()
Whenever it runs however, it only saves on of the function runs in the file, so instead of there being 9 pieces of data in the text file, there are only 3, which are the last 3 I input into the program. I can't figure out why it seems to be overwriting the data each time the function runs, does anyone know whats wrong with this code?
your problem is you are using the 'w' mode of an openfile.
just as you can open in mode 'r' for reading a file, you can use 'a' for appending to a file.
just change this line:
with open('employeeFile.txt', 'w') as dataFile:
to
with open('employeeFile.txt', 'a') as dataFile:
that should solve your problems!

Issue with conditional statement on external python file

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.

Categories

Resources