How to solve IndexError: list index out of range - python

Apologies, as I am new to the Programming world for asking novice question.
When I try to run the below code first time it is running fine, I can perform all the 3 operations perfectly, but when I try to run the same code again, I am getting an error as "list index out of range".
Any help and suggestions would be highly appreciated.
# To create a new file
ob=open(r'C:\Python27\avi_file_handling\cred_assgn.txt','w')
ob.write("Number" + "-" + "Username" + ":" + "Password" + '\n')
i=0
for x in range(5):
uid=raw_input("Please enter your username to login\n")
pswd=raw_input("Please enter your password {} to login\n".format(uid))
ob.write(str(i) + " " "-" " " + uid + " : " + pswd + '\n')
i=i+1
ob.close()
After creating the new file from the above code ,I ran the below code to call these operations.
import re
# function to validate the userId and password for the customers present in a text file
def validate_user():
T=0
global uid,pswd,T,c1,f1
f1=open(r'C:\Python27\avi_file_handling\cred_assgn.txt','r+')
f1.seek(0)
print f1.tell()
uid=raw_input("Please enter your username to validate\n")
print f1.tell()
pswd=raw_input("Please enter your password {} to validate\n".format(uid))
print f1.tell()
for line in f1:
c1=re.split(r'(-|:+|)',line.replace(' ','').strip())
if((uid==c1[2]) and (pswd==c1[4])):
print("welcome sir ",uid,"you are a valid user\n")
print f1.tell()
T+=1
return
else:
print("Sir",uid, "Please enter the correct Username and Password")
#Function to add a new user
def AddNew_User():
with open(r'C:\Python27\avi_file_handling\cred_assgn.txt','r+') as ob1:
uid=raw_input("Please enter username to Register\n")
ob1.seek(0,0)
z=0
print ob1.tell()
for line in ob1:
z=z+1
x=z
#z=sum(1 for _ in ob1)
c1=re.split(r'(-|:+|)',line.replace(' ','').strip())
if uid==c1[2]:
print "Sorry sir {},you are already registered, we cannot register you again".format(uid)
break
else:
pswd=raw_input("Please enter your password for userid {} to register\n".format(uid))
print ob1.tell()
if uid==pswd:
print "Sorry {} sir you cannot have same username and password".format(uid)
return
pswd2=raw_input("Please confirm your password once again for userid {} to register\n".format(uid))
print ob1.tell()
if pswd!=pswd2:
print "You have entered incorrect confrim password"
return
print ob1.tell()
print "Hello {} you have successful registered to us".format(uid)
print ob1.tell()
ob1.write(str(x) + " " "-" " " + uid + " : " + pswd + '\n')
print ob1.tell()
ob1.close()
#Function to update the password of an Existing user
def Update_password():
#print "up" ,f1.tell()
#global f1
validate_user()
#print "up" ,f1.tell()
print "previous one",c1
if T>0:
#print "up" ,f1.tell()
pswd3=raw_input("Hello {} Please entrer your new password")
#print "-up" ,f1.tell()
pswd4=raw_input("Hello {} once agin password")
print "1--up" ,f1.tell()
print pswd,pswd4,pswd3,uid
if pswd==pswd3:
print "Please enter the new password and do not repeat"
elif pswd3==pswd4:
#print "---up" ,f1.tell()
print c1[4]
print "11--up" ,f1.tell()
f1.seek(0)
ch=f1.read().replace(c1[4],pswd4)
print "2----up" ,f1.tell()
print ch
print "3----wup" ,f1.tell()
#ob.seek(2)
print "4----qup" ,f1.tell()
f1.seek(2)
f1.write(ch)
print "5----qup" ,f1.tell()
#contents = f.read().replace('Total: __00__', total)
#print "up" ,f1.tell()
print "poassower matcg"
#ob.seek(0,0)
f1.close()
#Main function calling
while(True):
Inputs=input("Please select the operation you would like to perform sir\n 1) Valudate user\n 2) Add new user \n 3) Update password \n5)Exit from the program")
if Inputs==1:
validate_user()
elif Inputs==2:
AddNew_User()
elif Inputs==3:
Update_password()
elif Inputs==5:
break

Related

PYTHON LOGIN SYSTEM

def loginadmin():
checker = -1
print (" \n******* ADMIN Login *******\n")
id = input("ID: ")
pw = input("Password: ")
with open ("adminid.txt", "r") as adminlogin:
for rec in range (0,len(adminlogin)):
if (userid == adminlogin[rec][0]) and (pw == adminlogin[rec][1]):
checker = rec
break
else:
return flg
adminlogin.close
status = loginadmin()
if (status != -1):
print (" \n******* Login Successful *******\n")
print ("Welcome Admin ", adminlogin[status][2])
else:
print (" \n******* user not found *******\n")
loginadmin ()
loginadmin()
what did i do wrong? trying to create a login system for my assignment.
i need to find id in txt file and password too.
make sure the password belongs to the id

need help in simple multiple login in python

i am trying to make a simple login system for python. i tried several things using break,return. but i cant get pass the login system using the second line in the text file onwards. i can only login through the first line of the text file, i took the code fro an other question but didnt know how to get it to work so i tried to change it so i could understand how it can work. I am extremely new to python. please let me know where i got wrong and how i can change it to get it to work!
format for user.txt is
first name|last name|occupation|id|username|password
John|goh|worker|1|admin|1234
import datetime
def check():
x = 0
users = open("users.txt").read().split("\n")
for i in range(len(users)): users[i] = users[i].split("|")
while (x < 3):
username = str(input("Username: \n"))
password = str(input("Password: \n"))
f = open('project_AI.txt', 'a')
f.write(str(datetime.now()))
f.write('\n' + username + '\n')
f.write(password + '\n')
f.close()
for user in users:
uname = user[4]
pword = user[5]
if uname == username and pword == password:
print("Hello " + user[1] + ".")
print("You are logged in as: " + user[2] + '.')
x += 3
else:
print('error')
check()
x += 1
return
check()
many thanks!!
I think the "return" in the penultimate line is at the wrong indentation, and isn't really needed at all.
As soon as python touches a return, it instantly destroys the function. In your code, after every user it checks, it hits the return. Meaning it will never even reach the second user.
You also want to not use check() within the function, as it will create a clone of itself within itself. The while x < 3 will go through the logic multiple times for you.
import datetime
def check():
x = 0
users = open("users.txt").read().split("\n")
for i in range(len(users)): users[i] = users[i].split("|")
while (x < 3):
username = str(input("Username: \n"))
password = str(input("Password: \n"))
f = open('project_AI.txt', 'a')
f.write(str(datetime.now()))
f.write('\n' + username + '\n')
f.write(password + '\n')
f.close()
for user in users:
uname = user[4]
pword = user[5]
if uname == username and pword == password:
print("Hello " + user[1] + ".")
print("You are logged in as: " + user[2] + '.')
x += 3
return
print('error')
x += 1
check()

How to exit while loop properly?

I have a program that runs through a list of names in 'serverlist.txt'.
The user selects the database they want to search in by choosing option 1 or option 2.
The program will run through all names in the list and provide the id tied to each name.
Name: Jupiter ID: 23
Name: Mars ID: 26
Name: Mercury ID: 27
This works fine but it doesn't stop. When the list is complete, it loops through everything all over again.
How do I stop it from going through the list more than once?
import pypyodbc
import os
def replaceid(connection, servername):
try:
cursor = connection.cursor()
SQLCommand = ("SELECT Name, Location_ID "
"FROM dbo.Server_ID " # table name
"with (nolock)"
"WHERE Name = ?")
Values = [servername]
cursor.execute(SQLCommand,Values)
results = cursor.fetchone()
if results:
print (" Name: " + results[0] + " ID: " + str(results[1]))
print (" ")
locationid(results, connection, servername)
else:
print (" ID for " + servername + " does not exist.")
print (" ")
connection.close()
except:
print("Database is down or you are not connected to network.")
exit()
def start1():
os.system('cls' if os.name == 'nt' else 'clear')
array = []
local = input('\n\n Type option 1 or 2: ')
while True:
with open("serverlist.txt", "r") as f:
for servername in f:
try:
if local in ['1']:
connection = pypyodbc.connect('Driver={SQL Server};Server=db1;Database=WinOasis;Trusted_Connection=yes;')
elif local in ['2']:
connection = pypyodbc.connect('Driver={SQL Server};Server=db2;Database=WinOasis;Trusted_Connection=yes;')
else:
return
except pypyodbc.Error as ex:
sqlstate = ex.args[0]
if sqlstate == '28000':
print ("You do not have access.")
replaceid(connection, servername.strip())
return
start1()
I think your return statement on the third to last line needs to be indented one level. Otherwise your while loop will run forever, because True will always be true!
You might want to add a break statement after you call replaceid(connection, servername.strip()) in start1()
You might also want a break statement after the exception clause ends.

PYTHON: How can I add +1 to a number in a file (txt.)

Okay so, I'm trying to make this little nifty auction program (for habbo if you've played it, but that's irrelevant.) Essentially, I have gotten pretty far with it, but my main goal is to be able to view Items (including their IDs for easy access) and to create new Items if I want.
Currently viewing items works fine, yet I'm struggling with the second goal, adding items.
I've used a bunch of different methods i've found on the internet, but none really seem to give the desired effect. I want to have a specific text document ("ID.txt") which simply starts at "0" and then each time my program is about to add an item, it adds 1 to that number in the file, so that I can call on it and give a brand new ID. So far each attempt I have it has done things like add [1] to the answer, instead of adding 1 itself.
import sys
import time
def choice1():
print("#####################################################")
print("Auction log opening")
dotDot = "..."
for char in dotDot:
sys.stdout.write(char)
time.sleep(0.5)
print("")
print("1 - Choose an item ID")
print("2 - Add an item")
print("3 - Return to start")
choices = input("Please make your choice. ")
if choices == "1" and "#1" and "one":
itemID = input("Enter item ID: ")
if itemID == "#0001":
aLog = open("auctionlist.txt")
lines = aLog.readlines()
print("#####################################################")
print("")
print(lines[0])
print(lines[1])
print(lines[2])
print(lines[3])
print("")
print("#####################################################")
elif itemID == "#0002":
aLog = open("auctionlist.txt")
lines = aLog.readlines()
print("#####################################################")
print("")
print(lines[4])
print(lines[5])
print(lines[6])
print(lines[7])
print("")
print("#####################################################")
elif choices == "2" and "#2" and "two":
## itemName = input("What's the item's name? ")
## itemBought = input("Item buy price? ")
## itemAvg = input("Item average? ")
## itemSell = input("Target sell price? ")
ID = open("ID.txt", "r+")
content = ID.readlines()
content[0] = content[0]+"1"
ID.write(str(content))
ID.close()
print("#####################################################")
print("Title: Auction House v0.1")
print("Author: Alasdair Cowie")
print("Date: 08/07/15")
print("#####################################################")
print("1 - Open the auction log.")
print("2 - Open the copy/paste log.")
print("3 - Exit the program")
oneTwoThree = input("Please make your choice. ")
if oneTwoThree == "1" and "one" and "#1" and "One":
choice1()
Open the file and read its contents:
with open(filePath) as idFile:
idString = idFile.read()
Convert the string to an int:
idNumber = int(idString)
Increase the number:
idNumber += 1
And write back that number:
with open(filePath, 'w') as idFile:
idFile.write('%d' % idNumber)
That's it.
You could use a replace method, and increment in your code,
you would search for i-1 and replace it with i or something similar.
print ("Text to search for:i-1")
textToSearch = input( "> " )
print ("Text to replace it with:i")
textToReplace = input( "> " )
print ("File to perform Search-Replace on:")
fileToSearch = input( "> " )
fileToSearch = 'D:\dummy1.txt'
tempFile = open( fileToSearch, 'r+' )
for line in fileinput.input( fileToSearch ):
if textToSearch in line :
print('Match Found')
else:
print('Match Not Found!!')
tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()
input( '\n\n Press Enter to exit...' )

Finding Hash's in text files

I'm am trying to verify users using a text document but not having much success. Can someone please point me in the right direction? Here is my code. What I want to do is have have python look on the line which contains the hash and then verify the hash. It is able to verify the first hash but nothing after that. Does anyone know how to fix this?
def passwordVerify():
global hashOne
f = open("maindata.txt")
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
numberOne = userConfirm + 2
numberTwo = userConfirm + 1
for line in islice(f, numberTwo, numberOne):
hashOne = line
hashStripped = str.rstrip(hashOne)
hashchecker = sha256_crypt.verify(passWord, hashStripped)
f.close()
if hashchecker is True:
loggedIn()
else:
print "Please try again!"
time.sleep(2.5)
userLogin()
def userRegister():
screenClear()
print "!King of Hearts Registration System!"
realName = raw_input("What is your real name: ")
userName = raw_input("Choose a Username: ")
passWord = getpass.getpass("Please enter a password: ")
passHash = sha256_crypt.encrypt(passWord)
writeUser = "\n" + userName + "\n"
writePass = passHash
userDB = open("maindata.txt", "a")
userDB.write(str(writeUser))
userDB.write(str(writePass))
userDB.close()
print passHash
userLogin()

Categories