I have a passwd.txt file which is formatted below and i want to create a module. this module should take each line separate it by ":" and save the 3 values, userName, realName and password variables. as i will use this functionality in 3 separate smaller programs. One will be used in a login as it takes username and passwords and will grant access or not, delete user program that takes the username then deletes that username from the file and a change password program that asks for username and old password checks it against the values return from the module then the new password to replace the old. these are all run from terminal and all are used to compare rather user name or password
userName:realName:password
etc
this is my code it worked until i tried to make it into a module and now only works if the last line is being compared, first time trying to reuse a block of code for multiple tiny programs. found it tricky as login, changepasswd, deluser and adduser are separate python files
def splitWordFile():
with open("passwd.txt") as file:
for line in file:
separatingData = line.split(":")
userName = separatingData[0]
if len(userName) > 1:
realName = separatingData[1]
actualPassword = separatingData[2].strip()
else:
continue
return userName, realName, actualPassword
You'll find your function easier to use if you convert it to a generator. As written, your function will only ever return the last observed userName, realName and actualPassword
Let's assume that passwd.txt looks like this:
aaa:bbb:ccc
xxx:yyy:xxx
...then...
FILENAME = "passwd.txt"
def splitWordFile(filename):
with open(filename, "r") as data:
for line in map(str.strip, data):
if len(tokens := line.split(":")) == 3 and len(tokens[0]) > 1:
yield tokens
for userName, realName, actualPassword in splitWordFile(FILENAME):
print(f"{userName=}, {realName=}, {actualPassword=}")
Output:
userName='aaa', realName='bbb', actualPassword='ccc'
userName='xxx', realName='yyy', actualPassword='xxx'