I am fairly new to code and i have a problem in reading a text file.
For my code i need to ask the user to type in a specific name code in order to proceed to the code. However, there are various name codes the user could use and i don't know how to make it so if you type either code in, you can proceed.
For example the text file looks like this
john123,x,x,x
susan233,x,x,x
conor,x,x,x
What i need to do is accept the name tag despite what one it is and be able to print it after. All the name tags are in one column.
file = open("paintingjobs.txt","r")
details = file.readlines()
for line in details:
estimatenum = input ("Please enter the estimate number.")
if estimatenum = line.split
This is my code so far, but i do not know what to do in terms of seeing if the name tag is valid to let the user proceed.
Here is another solution, without pickle. I'm assuming that your credentials are stored one per line. If not, you need to tell me how they are separated.
name = 'John'
code = '1234'
with open('file.txt', 'r') as file:
possible_match = [line.replace(name, '') for line in file if name in line]
authenticated = False
for item in possible_match:
if code in tmp: # Or, e.g. int(code) == int(tmp)
authenticated = True
break
You can use a module called pickle. This is a Python 3.0 internal library. In Python 2.0, it is called: cPickle; everything else is the same in both.
Be warned that the way you're doing this is not a secure approach!
from pickle import dump
credentials = {
'John': 1234,
'James': 4321,
'Julie': 6789
}
dump(credentials, open("credentials.p", "wb"))
This saves a file entitled credentials.p. You can the load this as follows:
from pickle import load
credentials = load(open("credentials.p", "rb"))
print(credentials)
Here are a couple of tests:
test_name = 'John'
test_code = 1234
This will amount to:
print('Test: ', credentials[test_name] == test_code)
which displays: {'John': 1234, 'James': 4321, 'Julie': 6789}
Displays: Test: True
test_code = 2343
print('Test:', credentials[test_name] == test_code)
Displays: Test: False
Related
I have this Python code:
with open('save.data') as fp:
save_data = dict([line.split(' = ') for line in fp.read().splitlines()])
with open('brute.txt') as fp:
brute = fp.read().splitlines()
for username, password in save_data.items():
if username in brute:
break
else:
print("didn't find the username")
Here is a quick explanation; the save.data is a file that contains variables of Batch-file game (such as username, hp etc...) and brute.txt is a file that contains "random" strings (like what seen in wordlists used for brute-force).
save.data:
username1 = PlayerName
password1 = PlayerPass
hp = 100
As i said before, it's a Batch-file game so, no need to quote strings
brute.txt:
username
usrnm
username1
password
password1
health
hp
So, let's assume that the Python file is a "game hacker" that "brute" a Batch-file's game save file in hope of finding matches and when it does find, it retrieves them and display them to the user.
## We did all the previous code
...
>>> print(save_data["username1"])
PlayerName
Success! we retrieved the variables! But I want to make the program capable of displaying the variables it self (because I knew that "username1" was the match, that's why I chose to print it). What I mean is, I want to make the program print the variables that matched. E.g: If instead of "username1" in save.data there was "usrnm", it will surely get recognized after the "bruting" process because it's already in brute.txt. So, how to make the program print what matched? because I don't know if it's "username" or "username1" etc... The program does :p (of course without opening save.data) And of course that doesn't mean the program will search only for the username, it's a game and there should be other variables like gold/coins, hp etc... If you didn't understand something, kindly comment it and I will clear it up, and thanks for your time!
Use a dict such as this:
with open('brute.txt', 'r') as f:
# First get all the brute file stuff
lookup_dic = {word.strip(): None for word in f.readlines()}
with open('save.data', 'r') as f:
# Update that dict with the stuff from the save.data
lines = (line.strip().split(' = ') for line in f.readlines())
for lookup, val in lines:
if lookup in lookup_dic:
print(f"{lookup} matched and its value is {val}")
lookup_dic[lookup] = val
# Now you have a complete lookup table.
print(lookup_dic)
print(lookup_dic['hp'])
Output:
username1 matched and its value is PlayerName
password1 matched and its value is PlayerPass
hp matched and its value is 100
{'username': None, 'usrnm': None, 'username1': 'PlayerName', 'password': None, 'password1': 'PlayerPass','health': None, 'hp': '100'}
100
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.
I am creating a program which requires the user to make changes to the dictionary. I can do these with a normal dictionary, however I was advised to hold my data in 'sub dictionaries' like the one below.
I've tried to see if I can get it working by having it change the values for all of the fields in each entry, but even that doesn't seem to be working. I am quite new to python so please bear with me!
VDatabase = {
"1200033944833": {
'MAP' : 'XXXX',
'CODE' : '0123',
'Method': 'R',
'Code1': 'S093733736',
'Reg ID' : '01'
}
Search = input("Search ACCOUNT:")
tmp_dict = VDatabase.get(Search, None)
print(tmp_dict if tmp_dict else "No ACCOUNT Found. \"{}\"".format(Search))
VDatabase["CODE"] = input("Enter CODE:")
print("Changing CODE...")
I was looking to change the value of CODE to whatever the user Input is.
Unfortunately it doesn't do anything, I can alter a regular Dictionary, so I think it's due to it being a 'sub-dictionary' so how would I access these values?
Here in the line,
VDatabase["CODE"] = input("Enter CODE:")
You are trying to change the value of 'CODE' directly in VDatabase but not inside the sub-dictionary that you have searched for.
Search = str(input("Search ACCOUNT:"))
tmp_dict = VDatabase.get(Search, None)
print(tmp_dict if tmp_dict else "No ACCOUNT Found. \"{}\"".format(Search))
VDatabase[Search]["CODE"] = str(input("Enter CODE:"))
print(VDatabase[Search])
or
tmp_dict['CODE'] = str(input("Enter CODE:"))
You will see that the main dictionary has changed.
I have changed the input type to str so that the value won't be integer while searching.
The purpose of this form is to let users enter a lot of places (comma separated) and it'll retrieve the phone, name, website. Have it working in a python IDE, no problem, but having issues putting it into my webapp.
I'm getting the error Exception Value: Can't pickle local object 'GetNums.<locals>.get_data' at the line where a is assigned. I checked the type of inputText and verified that it is indeed a list. So, I'm not sure why it won't pickle.
def GetNums(request):
form = GetNumsForm(request.POST or None)
if form.is_valid():
inputText = form.cleaned_data.get('getnums')
# all experimental
inputText = inputText.split(',')
def get_data(i):
#DON'T FORGET TO MOVE THE PRIMARY KEY LATER TO SETTINGS
r1 = requests.get('https://maps.googleapis.com/maps/api/place/textsearch/json?query=' + i + '&key=GET_YOUR_OWN')
a = r1.json()
pid = a['results'][0]['place_id']
r2 = requests.get('https://maps.googleapis.com/maps/api/place/details/json?placeid=' + pid + '&key=GET_YOUR_OWN')
b = r2.json()
phone = b['result']['formatted_phone_number']
name = b['result']['name']
try:
website = b['result']['website']
except:
website ='No website found'
return ' '.join((phone, name, website))
v = str(type(inputText))
with Pool(5) as p:
a = (p.map(get_data, inputText))
# for line in p.map(get_data, inputText):
# print(line)
#code assist by http://stackoverflow.com/a/34512870/5037442
#end experimental
return render(request, 'about.html', {'v': a})
It's actually barfing when trying to pickle get_data, which is a nested function/closure.
Move get_data out of GetNums (and agh rename it to snake_case please) and it should work.
I am trying to delete my conversation from a chat log file and only analyse the other persons data. When I load the file into Python like this:
with open(chatFile) as f:
chatLog = f.read().splitlines()
The data is loaded like this (much longer than the example):
'My Name',
'08:39 Chat data....!',
'Other person's name',
'08:39 Chat Data....',
'08:40 Chat data...,
'08:40 Chat data...?',
I would like it to look like this:
'Other person's name',
'08:39 Chat Data....',
'08:40 Chat data...,
'08:40 Chat data...?',
I was thinking of using an if statement with regular expressions:
name = 'My Name'
for x in chatLog:
if x == name:
"delete all data below until you get to reach the other
person's name"
I could not get this code to work properly, any ideas?
I think you misunderstand what "regular expressions" means... It doesn't mean you can just write English language instructions and the python interpreter will understand them. Either that or you were using pseudocode, which makes it impossible to debug.
If you don't have the other person's name, we can probably assume it doesn't begin with a number. Assuming all of the non-name lines do begin with a number, as in your example:
name = 'My Name'
skipLines = False
results = []
for x in chatLog:
if x == name:
skipLines = True
elif not x[0].isdigit():
skipLines = False
if not skipLines:
results.append(x)
others = []
on = True
for line in chatLog:
if not line[0].isdigit():
on = line != name
if on:
others.append(line)
You can delete all of your messages using re.sub with an empty string as the second argument which is your replacement string.
Assuming each chat message starts on a new line beginning with a time stamp, and that nobody's name can begin with a digit, the regular expression pattern re.escape(yourname) + r',\n(?:\d.*?\n)*' should match all of your messages, and then those matches can be replaced with the empty string.
import re
with open(chatfile) as f:
chatlog = f.read()
yourname = 'My Name'
pattern = re.escape(yourname) + r',\n(?:\d.*?\n)*'
others_messages = re.sub(pattern, '', chatlog)
print(others_messages)
This will work to delete the messages of any user from any chat log where an arbitrary number of users are chatting.