Home Ask Login Register

Developers Planet

Your answer is one click away!

kingjhez February 2016

Searching and sorting in text files

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




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.


Pouria Hadjibagheri February 2016

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


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

Pouria Hadjibagheri February 2016

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

Post Status

Asked in February 2016
Viewed 2,094 times
Voted 14
Answered 2 times


Leave an answer

Quote of the day: live life