Split and strip output python - python

I am really having some issues with getting clean output from python after reading in a file.
Here is my code so far:
user_pass_list = []
count = 0
for Line in open(psw):
fields = Line.strip("\n").strip(",").split(":")
user_pass_list.append(fields)
count = count + 1
print (count)
for item in range (0, count):
print (user_pass_list[item])
Here is what I keep getting as output:
['administrator', 'admin']
['']
['administrator', 'password']
['']
['admin', '12345']
['']
['admin', '1234']
['']
['root', 'root']
['']
['root', 'password']
['']
['root', 'toor']
Here is the text file that I am trying to read in to a list.
administrator:admin
administrator:password
admin:12345
admin:1234
root:root
root:password
root:toor
Could someone please help me? What I want is for each field to have its own list.
users[0]="administrator"
passwords[0]="admin"
users[1]="administrator"
passwords[1]="password"
Any suggestions?

You could use 2 lists, users and passwords like this:
users = []
passwords = []
with open(psw, 'rb') as fin:
for line in fin.readlines():
fields = line.strip().split(':')
users.append(fields[0])
passwords.append(fields[1])
But I think it would be more useful to have a list of tuples:
credentials = []
with open(psw, 'rb') as fin:
for line in fin.readlines():
fields = line.strip().split(':')
credentials.append((fields[0], field[1]))

How about instead of fields you try to unpack it into two vars immediately, and wrap it in a try/except so if it doesn't unpack to exactly two fields, it simply fails and skips it?
for Line in open(psw):
try:
user, pswd = Line.strip("\n").strip(",").split(":")
user_pass_list.append([user, pswd])
count = count + 1
except:
pass
You might also want to strip spaces and tabs.

There are a number of different ways to do this...
The straight forward way:
up0 = []
with open('pwd.txt') as fp:
for line in fp:
words = line.split(':')
username, password = [w.strip() for w in words]
up0.append((username, password))
using a nested list comprehension:
up1 = [(username, password.strip())
for (username, password)
in [line.split(':') for line in open('pwd.txt').readlines()]]
if you're using Python 2.7 that could be written with a simple map:
up2 = [map(str.strip, line.split(':')) for line in open('pwd.txt').readlines()]
Python 3 requires that you wrap the map inside list(), or you could replace the map by a list comprehension:
up3 = [[w.strip() for w in line.split(':')] for line in open('pwd.txt').readlines()]
and finally for those times when you feel funky, regular expressions:
import re
up4 = re.findall(r'([^:]+):([^\s]+).*\n', open('pwd.txt').read())
there seems like there should be a solution using itertools too... ;-)
You can print them all out by e.g. (Python 2.7):
print "Count:", len(up0)
for item in up0:
print item
or (Python 3):
print("Count:", len(up0))
for username, password in up0:
print("username={}, password={}".format(username, password)
I would suggest using the up0 version if you want a recommendation..
[update]: just saw you wanted all the usernames in one array and the passwords in another...
The above code creates a list of tuples, as you can see by e.g. using pprint:
import pprint
pprint.pprint(up0)
gives
[('administrator', 'admin'),
('administrator', 'password'),
('admin', '12345'),
('admin', '1234'),
('root', 'root'),
('root', 'password'),
('root', 'toor')]
this can be easily converted to what you want by:
username, password = zip(*up0)
print 'username:', username
print 'password:', password
which gives
username: ('administrator', 'administrator', 'admin', 'admin', 'root', 'root', 'root')
password: ('admin', 'password', '12345', '1234', 'root', 'password', 'toor')

Related

Is there a way to write a correct-form json info to a .json file and read from it locally?

I am planning to use JSON file as a simple database, i am trying to append to it new entries and try to take my entries later.
This is the code i have:
import json
import time
try:
with open('json_database.json', 'r') as json_database:
profiles = json.load(json_database)
except FileNotFoundError:
profiles = []
while True:
answer = input('list info (l), write info (w), new info (a)').lower()
if answer == 'w':
break
elif answer == 'l':
print(profiles)
else:
username = input('username: ')
email = input('Email: ')
rating = input('Rating: ')
lichess_profiles.append({
'profile':{
'username': lichess_username,
'email': email,
'rating': rating
}
})
with open('json_database.json', 'w') as json_database:
json.dump(profiles, json_database)
Now i want to call the info from the JSON info ! thats what i added :
with open('json_database.json') as json_1:
result = json.load(json_1)
print(result['profile']['email'])
what is the reason of that ? what shall i add ?
i tried that code but it raise this error :
TypeError: list indices must be integers or slices, not str
The base item you are writing to the json file is a list, but you're treating it like a dictionary. It contains dictionaries, but you have to access it like a list:
print(result[0]['profile']['email'])
print(result[1]['profile']['email'])
# etc.

How to call and iterate through specific indexes of a dictionary?

I currently have code that prints out a username and their password by means of dictionary. The output is username:abc password:12345. Right now I have them all just printing out at the same time. My main goal is to be able to email these users based on their usernames, but of course I only want to include their username and password information. Not the whole list of information. So basically I want to be able to tell the specific user only their password. For example, I would want to send an email to user abc and that email should only contain their username and password. Then I would like to send an email to user xyz but that should only contain the password of user xyz. Is there a way I can make this happen?
I currently have everything from the dictionary printing. So all the usernames and passwords are being printed out. How can I iterate through these and send an email to each user with their password?
lines = []
User_Pass = {}
#Open output file and show only lines that contain 'Success'
with open("output.txt", "r") as f:
for line in f.readlines():
#Get rid of everything in line after 'Success'
if 'Success' in line:
lines.append(line[:line.find("Success")-1])
for element in lines:
parts = element.strip().split(":")
User_Pass.update({parts[0] : parts[1]})
for key, value in User_pass.items():
print('Username: ' + key + ' Password: ' + value)
I want to be able to email each username and tell them their password. I am really not sure how to go about this. Any help would be appreciated!
Assuming you have the dictionary constructed, you just ask it for the value associated with the key, which is the username:
user_pw = User_Pass.get(username)
this will return None if the username is not in the dictionary.
Suggest you research Python dictionaries for some examples. In your loop code, you have it a little backwards as well. Anytime you want to iterate through a dictionary (the right way) you want to do it with the keys, not the items, so to loop through all in your example:
for key in User_Pass.keys():
print (key, User_Pass.get(key) )
Only fill your User_Pass dictionary when you meet "username" or "password":
for element in lines:
key, value = element.strip().split(":")
if key in {"username", "password"}:
User_Pass.update({key: value})
A simple demonstration:
lines = [
"fullname:John Doe",
"username:jdoe",
"password:S3cRet",
"age:45",
]
User_Pass = {}
for element in lines:
key, value = element.strip().split(":")
if key in {"username", "password"}:
User_Pass.update({key: value})
print(User_Pass)
You get:
{'username': 'jdoe', 'password': 'S3cRet'}
Please, you should follow the naming conventions of the PEP8: "User_Pass" => "user_pass".

Best way to add dictionary entry and append to JSON file in Python

I have a need to add entries to a dictionary with the following keys:
name
element
type
I want each entry to append to a JSON file, where I will access them for another piece of the project.
What I have below technically works, but there are couple things(at least) wrong with this.
First, it doesn't prevent duplicates being entered. For example I can have 'xyz', '4444' and 'test2' appear as JSON entries multiple times. Is there a way to correct this?
Is there a cleaner way to write the actual data entry piece so when I am entering these values into the dictionary it's not directly there in the parentheses?
Finally, is there a better place to put the JSON piece? Should it be inside the function?
Just trying to clean this up a bit. Thanks
import json
element_dict = {}
def add_entry(name, element, type):
element_dict["name"] = name
element_dict["element"] = element
element_dict["type"] = type
return element_dict
#add entry
entry = add_entry('xyz', '4444', 'test2')
#export to JSON
with open('elements.json', 'a', encoding="utf-8") as file:
x = json.dumps(element_dict, indent=4)
file.write(x + '\n')
There are several questions here. The main points worth mentioning:
Use can use a list to hold your arguments and use *args to unpack when you supply them to add_entry.
To check / avoid duplicates, you can use set to track items already added.
For writing to JSON, now you have a list, you can simply iterate your list and write in one function at the end.
Putting these aspects together:
import json
res = []
seen = set()
def add_entry(res, name, element, type):
# check if in seen set
if (name, element, type) in seen:
return res
# add to seen set
seen.add(tuple([name, element, type]))
# append to results list
res.append({'name': name, 'element': element, 'type': type})
return res
args = ['xyz', '4444', 'test2']
res = add_entry(res, *args) # add entry - SUCCESS
res = add_entry(res, *args) # try to add again - FAIL
args2 = ['wxy', '3241', 'test3']
res = add_entry(res, *args2) # add another - SUCCESS
Result:
print(res)
[{'name': 'xyz', 'element': '4444', 'type': 'test2'},
{'name': 'wxy', 'element': '3241', 'type': 'test3'}]
Writing to JSON via a function:
def write_to_json(lst, fn):
with open(fn, 'a', encoding='utf-8') as file:
for item in lst:
x = json.dumps(item, indent=4)
file.write(x + '\n')
#export to JSON
write_to_json(res, 'elements.json')
you can try this way
import json
import hashlib
def add_entry(name, element, type):
return {hashlib.md5(name+element+type).hexdigest(): {"name": name, "element": element, "type": type}}
#add entry
entry = add_entry('xyz', '4444', 'test2')
#Update to JSON
with open('my_file.json', 'r') as f:
json_data = json.load(f)
print json_data.values() # View Previous entries
json_data.update(entry)
with open('elements.json', 'w') as f:
f.write(json.dumps(json_data))

Python return value without inverted commas

I have csv file:
shack_imei.csv:
shack, imei
F10, "5555"
code:
reader = csv.reader(open("shack_imei.csv", "rb"))
my_dict = dict(reader)
shack = raw_input('Enter Shack:')
print shack
def get_imei_from_entered_shack(shack):
for key, value in my_dict.iteritems():
if key == shack:
return value
list = str(get_imei_from_entered_shack(shack))
print list
which gives me "5555"
But I need this value in a list structure like this:
["5555"]
I've tried a lot of different methods, and they all end up with extra ' or""
EDIT 1:
new simpler code:
reader = csv.reader(open("shack_imei.csv", "rb"))
my_dict = dict(reader)
shack = raw_input('Enter Shack:')
imei = my_dict[shack]
print imei
"5555"
list(imei) gives me ['"5555"'], I need it to be ["5555"]
You can change your "return" sentence:
shack = raw_input('Enter Shack:')
print shack
def get_imei_from_entered_shack(shack):
for key, value in my_dict.iteritems():
if key == shack:
return [str(value)]
list = get_imei_from_entered_shack(shack)
print list
As far as I understand, you want to create a list containing the returned string, which you do with [ ]
list = [str(get_imei_from_entered_shack(shack))]
There are a few problems with this code, which are too long to tackle in comments
my_dict
my_dict = dict(reader) works only well if this csv is a collection of keys and values. If there are duplicate keys, this might give some problems
get_imei_from_entered_shack
Why this special method, instead of just asking my_dict the correct value. Even if you don't want it to trow an Exception when you ask for a shack that doesn't exists, you can use the dict.get(<key>, <default>) method
my_dict(shack, None)
does the same as your 4-line method
list
don't name variables the same as builtins
list2
if you want a list, you can do [<value>] or list(<value>) (unless you replaced list with your own variable assignment)
reader = csv.reader(open("shack_imei.csv", "rb"))
my_dict = dict(reader)
shack = raw_input('Enter Shack:')
imei = my_dict[shack]
imei = imei.replace('"',"")
IMEI_LIST =[]
IMEI_LIST.append(imei)
print IMEI_LIST
['5555']

Python: split string with delimiters from a list

I'd like to split a string with delimiters which are in a list.
The string has this pattern: Firstname, Lastname Email
The list of delimiters has this: [', ',' '] taken out of the pattern.
I'd like to split the string to get a list like this
['Firstname', 'Lastname', 'Email']
For a better understanding of my problem, this is what I'm trying to achieve:
The user shall be able to provide a source pattern: %Fn%, %Ln% %Mail% of data to be imported
and a target pattern how the data shall be displayed:
%Ln%%Fn%; %Ln%, %Fn; %Mail%
This is my attempt:
data = "Firstname, Lastname Email"
for delimiter in source_pattern_delimiter:
prog = re.compile(delimiter)
data_tuple = prog.split(data)
How do I 'merge' the data_tuple list(s)?
import re
re.split(re.compile("|".join([", ", " "])), "Firstname, Lastname Email")
hope it helps
Seems you want something like this,
>> s = "Firstname, Lastname Email"
>>> delim = [', ',' ']
>>> re.split(r'(?:' + '|'.join(delim) + r')', s)
['Firstname', 'Lastname', 'Email']
A solution without regexes and if you want to apply a particular delimiter at a particular position:
def split(s, delimiters):
for d in delimiters:
item, s = s.split(d, 1)
yield item
else:
yield s
>>> list(split("Firstname, Lastname Email", [", ", " "]))
["Firstname", "Lastname", "Email"]
What about splitting on spaces, then removing any trailing commas?
>>> data = "Firstname, Lastname Email"
>>> [s.rstrip(',') for s in data.split(' ')]
['Firstname', 'Lastname', 'Email']
You are asking for a template based way to reconstruct the split data. The following script could give you an idea how to progress. It first splits the data into the three parts and assigns each to a dictionary entry. This can then be used to give a target pattern:
import re
data = "Firstname, Lastname Email"
# Find a list of entries and display them
entries = re.findall("(\w+)", data)
print entries
# Convert the entries into a dictionary
dEntries = {"Fn": entries[0], "Ln": entries[1], "Mail": entries[2]}
# Use dictionary-based string formatting to provide a template system
print "%(Ln)s%(Fn)s; %(Ln)s, %(Fn)s; %(Mail)s" % dEntries
This displays the following:
['Firstname', 'Lastname', 'Email']
LastnameFirstname; Lastname, Firstname; Email
If you really need to use the exact template system you have provided then the following could be done to first convert your target pattern into one suitable for use with Python's dictionary system:
def display_with_template(data, target_pattern):
entries = re.findall("(\w+)", data)
dEntries = {"Fn": entries[0], "Ln": entries[1], "Mail": entries[2]}
for item in ["Fn", "Ln", "Mail"]:
target_pattern= target_pattern.replace("%%%s%%" % item, "%%(%s)s" % item)
return target_pattern % dEntries
print display_with_template("Firstname, Lastname Email", r"%Ln%%Fn%; %Ln%, %Fn%; %Mail%")
Which would display the same result, but uses a custom target pattern:
LastnameFirstname; Lastname, Firstname; Email

Categories