I'm new to Python and I'm trying to create a simple program for login which reads/writes the information to/from a text file, but I'm having an issue.
Let's say I have the following content in a text file:
mytest#gmail.com, testPass123
First the email and after the comma the password. How can I read those two separately?
I have used .split(',') but it stores the whole line.
If I run this:
email = []
for line in file:
email.append(line.split(','))
print(email[0])
I get the following output:
['mytest#gmail.com', ' testPass123\n']
I think your variable naming is confusing you here. If you name email accounts, things might become clearer:
accounts = []
for line in file:
accounts.append(line.strip().split(','))
for email, password in accounts:
print("Email:", email, "Password:", password)
You may be looking for multiple assignment
>>> a, b = "em#ail, pass".split(",")
>>> a
'em#ail'
>>> b
' pass'
Related
New to Python and would like to use it with Regex to work with a list of 5k+ email addresses. I need to change the encapsulate each address with either quotes. I am using \b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}\b to identify each email address. How would I replace the current entry of user#email.com to "user#email.com" adding quotes around the each of the 5k email addresses?
You can use re.sub module and using back-reference like this:
>>> a = "this is email: someone#mail.com and this one is another email foo#bar.com"
>>> re.sub('([A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,})', r'"\1"', a)
'this is email: "someone#mail.com" and this one is another email "foo#bar.com"'
UPDATE: If you have a file that want to replace emails in each line of it you can use readlines() like this:
import re
with open("email.txt", "r") as file:
lines = file.readlines()
new_lines = []
for line in lines:
new_lines.append(re.sub('([A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,})', r'"\1"', line))
with open("email-new.txt", "w") as file:
file.writelines(new_lines)
email.txt:
this is test#something.com and another email here foo#bar.com
another email abc#bcd.com
still remaining someone#something.com
email-new.txt (after running the code):
this is "test#something.com" and another email here "foo#bar.com"
another email "abc#bcd.com"
still remaining "someone#something.com"
Pretend I am making an email script. The user has already made a username and password, which has been stored in a text file so they can log in later at anytime.
The user needs to be able to log in. I want python to check that the users input matches the information in the text file from earlier, on their corresponding line. Capitalization doesn't matter.
The text file that was created initially reads:
johncitizen
johnspassword
My python script should read something like:
##Reads text file
guessusername = input('What is your username? ')
guesspassword = input('What is your password? ')
if guessusername.lower() = lines[0] and guesspassword = lines[1]:
##Grant access
I don't mind if capitalization is wrong, as long as the string itself matches up
Before first of all, what you are doing with plain text password storage is ill-advised. You should be using hashing+salting, or even better, pick a decent framework to work in and learn from how they do it.
First of all, your data storage format should be more record like:
user_id<tab>username<tab>password
user_id<tab>username<tab>password
user_id<tab>username<tab>password
In that case, you are able to read the file like this:
username = ... #user input
password = ... #user input
found_user_id = None
with open('pass.txt', 'rt') as f:
for line in f:
fields = line.split("\t")
if fields[1] == username and fields[2] == password:
found_user_id = fields[0]
break
#okay, here if found_user_id is not None, then you have found them
#if it is None, then you did not find them.
Truly, a database is much more useful than a text file, but this is how it works!
I am currently writing a program in Python that asks if you have a log in. If no, they proceed to create a username and password. If yes, they log in and their details are checked against a text file. The text file looks like this (Username then password):
whitehallj27
EXpass%20
Username2
EXPASSWORD%%%
james_27
password1234
I am trying to figure out a way of programming this as simply as possible. It seems to work, but isn't nearly as simple and doesn't really work how I thought it would. Here is the code snippet:
logins={}
usernames_passwords=open("UsernamesAndPasswords.txt","r")
count=0
for line in usernames_passwords:
count=count+1
count=count/2
usernames_passwords.close()
usernames_passwords=open("UsernamesAndPasswords.txt","r")
try:
for x in range(count):
username=usernames_passwords.readline()
password=usernames_passwords.readline()
logins[username]=password
except TypeError:
count=int(count+0.5)
for x in range(count):
username=usernames_passwords.readline()
password=usernames_passwords.readline()
logins[username]=password
usernames_passwords.close()
print(logins)
Also, how would I go about authenticating the username and password to check it's correct.
Many thanks,
James Duxbury
Assuming that variables user and passwd have the username and password provided by the user, then just read the file in two lines:
file_contents = []
with open("UsernamesAndPasswords.txt","r") as f: #use "with", it will auotamtically close the file
file_contents = f.readlines()
usernames = file_contents[0::2] #step by 2, take all elements starting at index 0
passwords = file_contents[1::2] #step by 2, take all elements starting at index 1
found_at_index = -1
for i in range(0,len(usernames)):
if user == usernames[i] and passwd == passwrods[i]:
found_at_index = i
break
if found_at_index >= 0 :
#do whatever you want, there is match
else:
#I don't know what you wanted to do in this case
Please read this for the with keyword and this for how to read a file nicelly.
Also this about the [::] syntax.
You could create a dictionary with the user names and passwords like this:
dict = {
'user-name': 'password-hashing',
'another-user': 'another-password'
}
after you've done it you can save this dict in a json file, and load its content when the user asks for login.
the docs for handling json files with python: https://docs.python.org/3/library/json.html
obs.: it will look simpler, but its not the best way of doing this king of thing
I have a requirement to find the user from the log.
I have a line of code from my log file. One of the strings in the line is a userid. I have the list of all userid also.
Is there any easy way to identify the userid mentioned in the line.
Eg: Calling Business function ProcessSOMBFCommitment_Sourcing from F4211FSEditLine for ND9074524. Application Name [P421002], Version [] (BSFNLevel = 3)
Here, ND9074525 is the user id. My intention is to identify the user from the line.
Other possible userid can be AB9074158, AC9074168, AD9074123, AE9074152
I do not want to loop through all the possible userid. I thought of creating a list of all userid's and find the userid used in line by some method. Not sure if it exists.
You can use this regex to fetch the user id:
[A-Z]{2}\d{7}
And then check against valid user ids.
Regex Demonstration
Code:
import re
users = ['AB9074158', 'AC9074168', 'AD9074123', 'AE9074152']
s = 'Calling Business function ProcessSOMBFCommitment_Sourcing from F4211FSEditLine for ND9074524. Application Name [P421002], Version [] (BSFNLevel = 3)'
pat = '[A-Z]{2}\d{7}'
user_id = re.search(pat, s).group(0)
print(user_id)
if user_id in users:
print("User accepted!")
else:
print("User not accepted")
Output:
'ND9074524'
'User not accepted'
Use a regex to find all strings that match the pattern of a userid; then you can see if any of them are actual userids.
I have created a username/ password in htpasswd file. In my python script file I would like to access the username value for further processing. How do I achieve that? I am using Linux OS.
The htpasswd format is `:", something that isn't terribly difficult to parse. Simply go through line by line and split on a colon, taking the first value:
usernames = []
with open("passwdfile") as htpwd:
for line in htpwd.readlines():
username, pwd = line.split(":")
usernames.append(username)
Or more consisely:
with open("passwdfile") as htpwd:
usernames = [line.split(":")[0] for line in htpwd.readlines()]