Python some strings to list - python

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] ]

Related

How can I permanently store user inputs automatically into the dictionary

users = {
"Hi":"HM123",
"alan": "12122",
"12": "11"
}
def adder():
new_user = input("Please enter user's name: ").strip()
new_pwd = ""
confirmer = "0"
while new_pwd != confirmer:
new_pwd = input("please enter a new Password: ").strip()
confirmer = input("please confirm your password: ").strip()
if new_pwd != confirmer:
print("passwords does not match!!")
users[new_user] = new_pwd
adder()
I used The dictionary as a collection of usernames and passwords to practice creating a simple functional login page.(i'm importing this as a module to my main file). and when I add new users and passwords this code above temporarily adds it to the dictionary but when I re-run the script and try the new user names and pwds it returns incorect username and password, bc they are not in the dictionary.
was hoping to find a way to add the new usernames and paswwords into the dictionary permanently just with user inputs without having to modify the dictionary my self.
Your dictionary (more or less) is stored in RAM which is voilatile - you cannot (or at least, you shouldn't try to) preserve it between different scripts run.
Thas is why people use databases - they are stored on disk and don't vanish unless something really bad happens ;)
The easiest what would suits your needs is to store them in a single json file. It is a format very similar to python dictionary. Python has json library that allows it to parse such file into pythons dict and the opposite - put the dict back into the file.
Here is the example:
import json
with open("users.json", "r+") as f:
# convert content of file users.json into users variable - it will be a dict
users = json.load(f)
def store_to_file(users):
with open("users.json", "w") as f:
# save the users dict into the file users.json in json format
json.dump(users, f, indent=4)
def adder():
...
store_to_file(users)
adder()
Do not forget to create the file users.json!
{
"Hi": "HM123",
"alan": "12122",
"12": "11"
}
Python dictionaries can be converted to JSON text and written to permanent storage as such.
You could also consider serialisation of the dictionary using the pickle module.
Here's an example of both techniques:
import pickle
import json
PFILE = '/Volumes/G-Drive/users.pkl'
JFILE = '/Volumes/G-Drive/users.json'
users = {
"Hi": "HM123",
"alan": "12122",
"12": "11"
}
with open(PFILE, 'wb') as db:
pickle.dump(users, db) # save the dictionary (serialise)
with open(PFILE, 'rb') as db:
_users = pickle.load(db) # retrieve serialised data
print(_users)
with open(JFILE, 'w') as db:
json.dump(users, db) # save as JSON
with open(JFILE) as db:
_users = json.load(db) # retrieve JSON and convert to Python dictionary
print(_users)
Output:
{'Hi': 'HM123', 'alan': '12122', '12': '11'}
{'Hi': 'HM123', 'alan': '12122', '12': '11'}

How to skip empty cells using csv.DictWriter

I am trying to anonymize data in CSV, however, I only want to do this for cells that are not empty. At present, my program adds anonymized data to all cells with the given row.
How can I skip empty the empty cells? Below is my program
import csv
from faker import Faker
from collections import defaultdict
def anonymize():
"Anonymizes the given original data to anonymized form"
faker = Faker()
names = defaultdict(faker.name)
emails = defaultdict(faker.email)
with open(filename, "r") as f:
with open(f"{filename}-anonymized_data.csv", "w") as o:
reader = csv.DictReader(f)
writer = csv.DictWriter(o, reader.fieldnames)
writer.writeheader()
for row in reader:
row["adult_First_Name"] = names[
row["adult_First_Name"]
]
row["child_First_Name"] = names[
row["child_First_Name"]
]
row["Adult - EMAIL ADDRESS"] = emails[row["Adult - EMAIL ADDRESS"]]
row["Parent - EMAIL ADDRESS"] = emails[row["Parent - EMAIL ADDRESS"]]
writer.writerow(row)
if __name__ == "__main__":
anonymize()
You could test each field before applying the fake value. A simpler approach would be to store the fields that need to be changed in a fields list along with which faker function to apply if needed:
import csv
from faker import Faker
def anonymize():
"Anonymizes the given original data to anonymized form"
faker = Faker()
fields = [
("adult_First_Name", faker.name),
("child_First_Name", faker.name),
("Adult - EMAIL ADDRESS", faker.email),
("Parent - EMAIL ADDRESS", faker.email),
]
with open(filename, "r") as f:
with open(f"{filename}-anonymized_data.csv", "w", newline="") as o:
reader = csv.DictReader(f)
writer = csv.DictWriter(o, reader.fieldnames)
writer.writeheader()
for row in reader:
for field, fake in fields:
if row[field]:
row[field] = fake()
writer.writerow(row)
if __name__ == "__main__":
anonymize()
Adding newline='' would stop extra blank lines in the output.

How to split a text file into a nested array?

Working on a project creating a python flask website that stores user logins into a text file. I have a text file where each line is one user and each user has 5 parameters stored on the line. All user parameters are separated by a ; character.
Parameters are:
username
password
first name
last name
background color
title
avatar
Sample of the text file:
joebob;pass1;joe;bob;yellow;My title!!;https://upload.wikimedia.org/wikipedia/commons/c/cd/Stick_Figure.jpg
richlong;pass2;rich;long;blue;My title2!!;https://www.iconspng.com/images/stick-figure-walking/stick-figure-walking.jpg
How do I go about storing the parameters into a python array, and how do I access them later when I need to reference log-ins.
Here is what I wrote so far:
accounts = { }
def readAccounts():
file = open("assignment11-account-info.txt", "r")
for accounts in file: #line
tmp = accounts.split(';')
for data in tmp: #data in line
accounts[data[0]] = {
'user': data[0],
'pass': data[1],
'first': data[2],
'last': data[3],
'color': data[4],
'title': data[5],
'avatar': data[6].rstrip()
}
file.close()
You can use the python builtin csv to parse
import csv
with open("assignment11-account-info.txt", "r") as file:
reader = csv.reader(file, delimiter=';')
result = []
for row in reader:
fields = ('user', 'passwd', 'first', 'last', 'color','title','avatar')
res = dict(zip(fields, row))
result.append(res)
Or equivalent but harder to read for a beginner the pythonic list comprehension:
with open("assignment11-account-info.txt", "r") as file:
reader = csv.reader(file, delimiter=';')
fields = ('user', 'passwd', 'first', 'last', 'color','title','avatar')
result = [ dict(zip(fields, row)) for row in reader ]
Here's what I might do:
accounts = {}
with open("assignment11-account-info.txt", "r") as file:
for line in file:
fields = line.rstrip().split(";")
user = fields[0]
pass = fields[1]
first = fields[2]
last = fields[3]
color = fields[4]
title = fields[5]
avatar = fields[6]
accounts[user] = {
"user" : user,
"pass" : pass,
"first" : first,
"last" : last,
"color" : color,
"title" : title,
"avatar" : avatar
}
By using with, the file handle file is closed for you automatically. This is the most "Python"-ic way of doing things.
So long as user is unique, you won't overwrite any entries you put in as you read through the file assignment11-account-info.txt.
If you need to deal with a case where user is repeated in the file assignment11-account-info.txt, then you need to use an array or list ([...]) as opposed to a dictionary ({...}). This is because reusing the value of user will overwrite any previous user entry you add to accounts. Overwriting existing entries is almost always a bad thing when using dictionaries!
If that is the case, I might do the following:
accounts = {}
with open("assignment11-account-info.txt", "r") as file:
for line in file:
fields = line.rstrip().split(";")
user = fields[0]
pass = fields[1]
first = fields[2]
last = fields[3]
color = fields[4]
title = fields[5]
avatar = fields[6]
if user not in accounts:
accounts[user] = []
accounts[user].append({
"user" : user,
"pass" : pass,
"first" : first,
"last" : last,
"color" : color,
"title" : title,
"avatar" : avatar
})
In this way, you preserve any cases where user is duplicated.

How to pull specific parts of a list on each line?

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.

Python script to create multiple users in a CSV file and generate email addresses

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] )

Categories

Resources