Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

How to read the database from another python file?

I had make a database from another python file.Now i want to read the database data from another python file.Please write the explaination by writing code in answer.

Good day. Is this part of a challange or just a general question?

Please post the code you used to create the database, and we can use that to start creating the code for reading seraratly.

from peewee import *
import re
import sys
from collections import OrderedDict
db=SqliteDatabase('password.db')
db2=SqliteDatabase('data.db')
class Password(Model):
    password=CharField(max_length=255)
    class Meta:
        database=db

class Data(Model):
    saved=CharField(max_length=25,unique=True)
    path=CharField(max_length=255)
    class Meta:
        database=db2

def add():
    """Add a new file"""
    print('Type the full path of the file')
    check=input('>>> ')
    name=open(check)
    data=name.read()
    name.close()
    t=input('Enter the full path where you want to save it ')
    write_on=open(t,"w")
    for a in data:
        b=str(encode[a])
        write_on.write('{} '.format(b))
    write_on.close()
    print('what is the name of the file?')
    o=input('>>> ')
    Data.create(saved=o,path=t)
    print('Saved sucessfully!')


def view():
    """view saved files"""
    count=1
    print('Type the name of the file which you want to open')
    for name in Data:
        print('{}) {}'.format(count,name.saved))
        count+=1
    u=input('>>> ')
    for name in Data:
        if u==name.saved:
            select=name.path
            break
    convert=[]
    q=open(select)
    data=q.read()
    q.close()
    d=re.findall(r'\d+ ',data)
    for no in d:
        d=encode2[int(no.strip())]
        convert.append(d)
    l=''.join(convert)
    print(l)

def change():
    """change the password"""
    print('type q to quit')
    e=input('type your old password: ')
    for a in Password:
        b=a.password
        a.delete_instance()
    if e==b:
        print('Type your new password')
        n=input('>>> ')
        Password.create(password=n)

encode={'a':0,'b':1,'c':10,'d':100,'e':110,'f':1111,'g':101,'h':11,'i':111,'j':1000,'k':1011,'l':1110110,'m':11011,'n':10100,'o':10111,'p':11101,'q':10001,'r':1100,'s':101110,'t':10110,'u':100110,'v':101001,'w':10001,'x':111001,'y':100010,'z':101101,' ':101000,'=':110110,'.':111111,'\n':111110}
encode2={0:'a',1:'b',10:'c',100:'d',110:'e',1111:'f',101:'g',11:'h',111:'i',1000:'j',1011:'k',1110110:'l',11011:'m',10100:'n',10111:'o',11101:'p',10001:'q',1100:'r',101110:'s',10110:'t',100110:'u',101001:'v',10001:'w',111001:'x',100010:'y',101101:'z',101000:' ',110110:'=',111111:'.',111110:'\n'}

menu=OrderedDict([
    ('a',add),
    ('b',view),
    ('c',change)
    ])

if __name__=='__main__':
    db.connect()
    db.create_tables([Password],safe=True)
    db2.connect()
    db2.create_tables([Data],safe=True)
    if b != None:
        while True:
            b=None
            try:
                for a in Password:
                  b=a.password
            except:
                b=None
            print("Type 'q' to quit")
            password=input('Enter your password: ')
            if password==b:
                for key,value in menu.items():
                    print('{}) {}'.format(key,value.__doc__))
                take=input('Action: ')
                if take in menu:
                    menu[take]()
            elif password.lower()=='q':
                sys.exit()

            else:
                print('wrong password')

    else:
        print('Enter your new password')
        new=input('> ')
        Password.create(password=new)
        print('New password created susscesfully\nclose the app and try again to continue')

Here's the code.now i am going to tell you that what this program does.This program read an .txt file and then convert it to 0 and 1 so no one can read that and in the program there is the password to open your locked file and then from there you can convert 0 and 1 to your old txt file so you can read it.This program doesn't have any error it work fine and donot have any error but i only want to read the password from another file so please tell me how can i do that and also run this program in your computer it is really good program but be sure to select the file which has only letters not any special character.

1 Answer

Quickly looking at your program, the password is not used to encrypt or decrypt the file, but only to access the menu items. You could very easily remove the need for the password altogether by changing the 'if name=='main':' as shown below.

    while True:
        for key,value in menu.items():
            print('{}) {}'.format(key,value.__doc__))
        take=input('Action: ')
        if take.lower() == 'q':
            break
        if take in menu:
            menu[take]()

To loop though the password database and print out all the passwords from a new file in the same directory as password.db:

from peewee import *

db=SqliteDatabase('password.db')
class Password(Model):
    password=CharField(max_length=255)
    class Meta:
        database=db

if __name__=='__main__':
    db.connect()
    db.create_tables([Password],safe=True)

    for entry in Password.select():
        print(entry.password)

Yes i only used the password so if someone run it then it will ask for password first But i still have a question that in my program i don't use the .select() in my for loop but that work fine so why we are using Password.select() for loop.i simple do this in my program by:

for a in Password:
    b=a.password