I have a document that holds login details as "username1, password1, username2, password2 etc." Is there a way of splitting them into two arrays that hold just usernames and just passwords?
I tried doing: usernames, passwords = login.split(",") but that's just a ValueError.
Sorry if it's something so obvious!
Update:
login = "username1, password1, username2, password2"
you are getting ValueError because login.split() returns a list with more than two elements.
If your data are formatted as username, password you can split and then slice the list:
login = "username1, password1, username2, password2"
data = login.split(",")
usernames = data[::2]
passwords = data[1::2]
My solution works on even and odd index of a list. If even index, then append to usernames, if odd index then to passwords.
login='username1, password1, username2, password2'
usernames, passwords = [], []
s = login.split(",")
for i in range(len(s)):
usernames.append(s[i]) if i%2 == 0 else passwords.append(s[i])
i believe you have the file structure like below:
username1, password1, username2, password2
username3, password3, username4, password4
username5, password5, username6, password6
username7, password7, username8, password8
then the below code will work ,
import csv
list_username=[]
list_pwd=[]
with open("untitled.txt") as f1:
csvrow=csv.reader(f1,delimiter=",")
for row in csvrow:
usernames = row[0] + "," +row[2]
passwords = row[1] + "," +row[3]
list_username.append(usernames)
list_pwd.append(passwords)
print(list_username)
print(list_pwd)
i have attached the output of the code as well,
Related
let's assume that program take these variables;
website = "https://stackoverflow.com/questions/"
username = "BestSithInEU"
password = "S0n'X%`2FU`,t!j-"
My aim that, I want to store these datas with another class;
class forExample:
self.header = ["website", "username / email", "password"]
self.data_list = [website, username, password]
### And I'm using this method from csv library
with open("password.csv", "a", encoding="UTF8", newline="") as f:
writer = csv.writer(f)
write multiple rows
writer.writerows(self.data_list)
How can I convert these three variables to list of strings? And also when I use this self.data_list I'm getting this output...
website
username/email
password
h,t,t,p,s,:,/,/,s,t,a,c,k,o,v,e,r,f,l,o,w,.,c,o,m,/,q,u,e,s,t,i,o,n,s,/
B,e,s,t,S,i,t,h,I,n,E,U
_csv.Error: iterable expected, not NoneType
The csv writer expects a list of lists. So
self.data_list = [ [website, username, password] ]
I have a list that spits out information like this: ['username', 'password'], ['username', 'password'], ['username', 'password'], and so on..
I would like to be able to pull a specific username and password later on.
For example:
['abc', '9876'], ['xyz', '1234']
pull abc and tell them the password is 9876.
Then pull xyz and tell them the password is 1234
I tried messing around with the list and I am just drawing a blank on how to do this.
lines = []
with open("output.txt", "r") as f:
for line in f.readlines():
if 'Success' in line:
#get rid of everything after word success so only username and password is printed out
lines.append(line[:line.find("Success")-1])
for element in lines:
#split username and password up at : so they are separate entities
#original output was username:password, want it to be username, password
parts = element.strip().split(":")
print(parts)
I want to pull each username and then pull their password as described above
Current output after running through this is ['username', 'password']. The original output file had extra information that I got rid of which is what the code involving 'Success' took care of
I would like to do this without hardcoding a username in to it. I am trying to automate this process so that it runs through every username and formats it to say, "hi [username}, your password is [123]", for all of the usernames
I then later would like to be able to only tell the specific user their password. For example, i want to send an email to user abc. that email should only contain the username and password of user abc
Instead of printing parts, append them to a list.
data = []
for element in lines:
parts = element.strip().split(":")
data.append(parts)
Then you could convert these into a dictionary for lookup
username_passwords = dict(data)
print(username_passwords['abc'])
If I am understanding this correctly parts is the list that contains [Username:Password]. If that is the case we can assign each value of parts which should only have 2 elements in it to a dictionary as a dictionary pair and then call the username later on.
lines = []
User_Pass = {}
with open("output.txt", "r") as f:
for line in f.readlines():
if 'Success' in line:
#get rid of everything after word success so only username and password is printed out
lines.append(line[:line.find("Success")-1])
for element in lines:
#split username and password up at : so they are separate entities
parts = element.strip().split(":")
User_Pass.update({parts[0] : parts[1]})
Then you can call the password from the username as follows if you know the username:
x = User_Pass["foo"]
Or as you stated in the comments:
for key, value in User_Pass.items():
print('Username ' + key + ' Has a Password of ' + value)
it looks like after you do this
lines.append(line[:line.find("Success")-1])
lines = ['username:password', 'username:password'...]
so I would do this
new_list_of_lists = [element.strip().split(":") for element in lines]
new_list_of_lists should now look like [[username, password], [username, password]]
then just do this:
dict_of_usernames_and_passwords = dict(new_list_of_lists)
with a dict you can have now retrieve passwords using usernames. like:
dict_of_usernames_and_passwords['abc']
you can save the dict, using json module, to a file, for easy retrieval.
I have the following code in Python 3.6.0. I am a newbie and have been trying to get this code to work. I don't know how to get python to recognize (and reject) if the user enters the same username with capitals letters; below is the code.
I would appreciate if you can show me how, please avoid comprehensions, just show me the full length code: (since "albert" is entered in new_user, I want the program to reject the user name since it is in the current_user in title letters.
current_user = ["John","Peter","sam","Albert"]
new_user = ["albert"]
for name in new_user:
if name.lower() in current_user:
print ("Sorry Username is taken, please enter a new username")
else:
print ("Username accepted")
This is a situation where comprehensions really shine - however if you want to do it the long way, one option is:
current_user = ["John","Peter","sam","Albert"]
new_user = ["albert", "george", "John", "FRED"]
for new in new_user:
name_ok = True
for current in current_user:
if new.lower() == current.lower():
print ("Sorry {} is taken, please enter a new username".format(new.lower()))
name_ok = False
break
if name_ok:
print ("Username {} accepted".format(new.lower()))
I am importing contacts from gmail. c_lst is the list that has the names and email address in a dictionary as follows - [{'name': u'fn1 ln1', 'emails': [u'email1#gmail.com']}, {'name': u'fn2 ln2', 'emails': [u'email2#gmail.com']},.
There are two problems with importing contacts:
Some of the contacts that I might be importing, might already be present in the database, in that case, I do not want to add another contact.
Unique usernames. There is a possibility of two emails being same, except the domain names. eg. email#gmail.com and then email#outlook.com in that case, I need to have distinct usernames so the first username would be like email, and the second one would be email1.
I have implemented both of them, and commented for making things clear.
Can there be more pythonic way of doing it?
for contact in c_lst:
email = contact.get('emails')[0]
name = contact.get('name').split(' ')
first_name, last_name = name[0], name[-1]
try:
# check if there is already a user, with that email address
# if yes then ignore.
u = Users.objects.get(email = email)
print "user exists"
except:
while True:
username = email.split('#')[0]
name, idx = username, 1
try:
# user with current username exists, so add numeral
Users.objects.get(username = username)
name = username + str(idx)
except User.DoesNotExist:
username = name
u = User.objects.create(username = username, email = email, first_name = first_name, last_name = last_name)
u.save()
break
Please let me know, of any other/better flow/approach.
For generating usernames, one might advice generating random numbers, but its okay for me
to go sequentially, as it is only one time activity.
The one thing I would like to change is to handle the first except explicitly. Since you are using:
u = Users.objects.get(email=email) # don't add space before and after "=" in argument
It could raise a MultipleObjectsReturned exception then create an infinite loop in the current except block.
So you should at least change your code to:
# ... your code ...
first_name, last_name = name[0], name[-1]
try:
u = Users.objects.get(email=email)
except User.DoesNotExist:
# ... your code ....
except User.MultipleObjectsReturned:
# handle this case differently ?
Well your might want to handle the second try except block similarly but that's your choice.
Hope this helps.
I want to create a csvfile that has multiple users and at the same time create email addresses for this users using their last names. I am using python for this but I can't get it to create the e-mail address in the list. My script is below, what am I missing?
import csv
First_Name = ["Test"]
Last_Name = ["User%d" % i for i in range (1,10)]
Email_Address = 'Last_Name' [("#myemail.com")]
Password = ["Password1"]
# open a file for writing.
csv_out = open('mycsv.csv', 'wb')
# create the csv writer object.
mywriter = csv.writer(csv_out)
# all rows at once.
rows =zip(Email_Address, Password, First_Name, Last_Name,)
mywriter.writerows(rows)
csv_out.close()
Make
Email_Address = 'Last_Name' [("#myemail.com")]
into
Email_Address = [x + "#myemail.com" for x in Last_Name]
to create a list of all email addresses based on all last names. This assumes you intended for all of your variables to be lists.
Even though this will create ten emails (one for each last name) your file will only have one row written to it. This is because zip will stop iteration at the length of the shortest list you pass it. Currently First_Name and Password each contain only one item.
I'm basically guessing since you haven't said anything about what errors you're getting, but the most obvious problem I can see is that you're trying to add a string to a list of tuples, which doesn't make a lot of sense.
'Last_Name' [("#myemail.com")]
should be:
'Last_Name' + "#myemail.com"
Now, as far as what you're actually trying to do, which is extremely unclear, I think you want to use a series of list comprehensions. For example:
users = [i for i in range(0, 10)]
first_names = ["test"+str(user) for user in users]
last_names = ["User%d" %user for user in users]
email_addresses = [last_name + "#myemail.com" for last_name in last_names]
passwords = ["Password1" for user in users]
with open('mycsv.csv', 'wb') as csv_out:
writer = csv.writer(csv_out)
writer.writerows(zip(email_addresses, passwords, first_names, last_names))
output:
User0#myemail.com,Password1,test0,User0
User1#myemail.com,Password1,test1,User1
User2#myemail.com,Password1,test2,User2
User3#myemail.com,Password1,test3,User3
User4#myemail.com,Password1,test4,User4
User5#myemail.com,Password1,test5,User5
User6#myemail.com,Password1,test6,User6
User7#myemail.com,Password1,test7,User7
User8#myemail.com,Password1,test8,User8
User9#myemail.com,Password1,test9,User9
Your zip() will only produce a list w/ 1 item b/c First_Name and Password explicitly each contain only 1 item.
How about this, avoiding the zip entirely:
with open('mycsv.csv', 'wb') as csv_out:
writer = csv.writer(csv_out)
for i in xrange(1,9):
writer.writerow( ["User%d#myemail.com"%i, "Password%d"%i, "test%d"%i, "User%d"%i] )