Withopen module and mainsheet cycles

Joined
Jan 26, 2023
Messages
9
Reaction score
0
Python:
#Hi there ! friend n! I need help.Persians attack from the south. We need more triremis!
#the case is I can not realize. How to relate my module with main shee. There we input some
#data and immediately can get back data writting num 1.

#Module

def save_inf(info):
    with open('file.txt','w') as f:
        for lama in info:
            f.write(input('data:'))

        return lama

def load_inf():
    with open('file.txt','r') as f:
        data=f.read()
        info={}
        for lama in data:
            if lama:
                lama=lama
                lama=input('back data:')
-----------------------------------------------------
#Main sheet

while True:
    u=input('data:')
    save()
    #save()
    #while True:
    p=load(input('back data'))
      
    if p=='1':
        print(f.read())
 
Joined
Dec 10, 2022
Messages
73
Reaction score
22
Read up on classes and the mcv approach. That would simplify thing greatly for you.
 
Joined
Dec 10, 2022
Messages
73
Reaction score
22
Here is an example of using the mcv approach. I will leave the reading and writing to you but, I did setup an example menu.

Python:
class Model:
    '''
    Model does all the reading and writing to ur file
    '''
    def __init__(self):
        pass

    def write(self, file):
        with open(file, 'w') as doc:
            doc.write(input('data: '))

    def read(self, file):
        with open(file, 'r') as doc:
            data = doc.read()
            return data

class View:
    '''
        View will display out file content and other options/messages
    '''
    def __init__(self, file=None):
        self.file = file


    def show(self, arg):
        print(f'\n{arg}\n')


class Controller:
    '''
        Controller does the communications between our view and model
    '''
    def __init__(self, model, view):
        self.model = model
        self.view = view

        self.menu = {
            'Add Data': 1,
            'Read Data': 2,
            'Exit': 3
        }


if __name__ == '__main__':
    controller = Controller(Model(), View())

    while True:
        for item, option in controller.menu.items():
            print(f'{item} : {option}')
        try:
            op = int(input('>> '))
            if op in controller.menu.values():
                if op == 3:
                    controller.view.show('Goodbye!')
                    break
                else:
                    controller.view.show(f'You chose option {op}')
            else:
                controller.view.show(f'\nThat is not a valid option.\n')
        except ValueError:
            print('\nError!, That is not a valid entery.\n')
 
Joined
Dec 10, 2022
Messages
73
Reaction score
22
Here is an example that writes and reads a text file.

Python:
# Do the imports
from pathlib import Path

# Set file path
path = Path('test.txt')

class Model:
    '''
    Model does all the reading and writing to ur file
    '''

    # Give prompt and writes data entered to text file
    def write(self):
        with open(path, 'a') as doc:
            doc.write(input('data: ')+'\n')

    # Opens text file and grabs contents for return
    # If a file does not exist returns message
    def read(self):
        if path.is_file():
            with open(path, 'r') as doc:
                    data = doc.read()
                    return data
        return 'You need to add data for a file to be created for reading.\n'

class View:
    '''
        View will display out file content and other options/messages
    '''

    def show(self, arg):
        # Displays data
        print(f'\n{arg}')


class Controller:
    '''
        Controller does the communications between our view and model
    '''
    def __init__(self, model, view):
        # Set class variables
        self.model = model
        self.view = view

        # Create a menu. Using a dict to have some text to display and an int to perform select action
        self.menu = {
            'Add Data': 1,
            'Read Data': 2,
            'Exit': 3
        }


if __name__ == '__main__':
    # Initiate classes
    controller = Controller(Model(), View())

    # While loop so code doesn't just exicute the quit
    while True:
        # Loop through and display menu
        for item, option in controller.menu.items():
            print(f'{item} : {option}')

        # Try block to test entry and to keep code from continueos scrolling text
        try:
            op = int(input('>> '))

            # Test if entered option is valid. If it's not within the menu option throw error.
            if op in controller.menu.values():
                if op == 3:
                    # if option 3 is selected exit program
                    controller.view.show('Goodbye!')
                    break
                else:
                    # Else either option 1 write entered text or option 2 display text file contents
                    if op == 1:
                        controller.model.write()
                    if op == 2:
                        controller.view.show(controller.model.read())
            else:
                controller.view.show(f'\nThat is not a valid option.\n')
        except ValueError:
            print('\nError!, That is not a valid entery.\n')
 
Joined
Jan 26, 2023
Messages
9
Reaction score
0
#Thank you a lot. Your work is just something else! although, too difficult for my at the moment. Here is an easy option_ for start.
#There is some tricky thing I try to understand if I write def save_data(information): information is not define on the main sheet. As #long as information erased it write save_data() require one important argument information. Sorry provided these questions are #genius.
#Modul
Python:
def save_data():
    with open('file.txt','w') as f:
        f.write(input('data:'))


def load_data():
    with open('file.txt','r') as f:
        for one in f:
            print(one)

-----------------------------------------------------------------------------------------------------------------------------
#Main
Python:
while True:
    p=print('1 save, 2 show')
    p=input()
    if p=='1':
        save_data()
    elif p=='2':
        load_data()
 
Joined
Dec 10, 2022
Messages
73
Reaction score
22
information is an argument passed to the function

Maybe this will help

Python:
# Information is just an argument passed to the function.
# If you don't pass an argument it will error
def save(information):
    print(information)

# If you run this without an argument, it will error
# save()

# You can set a default argument to pass
def save2(information='Some default argument'):
    print(information)

# This will print the default argument
save2()

# Pass an argument to the function
# It will print the string passed as an argument
save('This is a passed argument')
 
Joined
Dec 10, 2022
Messages
73
Reaction score
22
This is about as simple as I know

Python:
# Import Path from pathlib. This will give a file path and allow us to test
# if the file exist
from pathlib import Path

# Create the file path. This will be the current project directory
file = Path('file.txt')

# Define the function for saving input data
# Opens the file and ask for input then writes
# w will overwrite the current file. Use a to append data
def save():
    with open(file, 'w') as f:
        f.write(input('data: '))

# Define a function for loading and reading the file
# We use file.is_file() for testing if the file exist.
# If the file does not exist give an error message
def load():
    if file.is_file():
        with open(file, 'r') as f:
            print(f.read())
    else:
        print('File does not exist')


# Start the while loop
while True:

    # Print out the menu
    print('1 Save, 2 Show, 3 Exit')

    # Prompt
    p = input('>> ')

    # If 1 is entered, call the save function
    # If 2 is entered, call the load function
    # If 3 is entered, exit the program
    # Else print an error, because no proper input was entered
    if p == '1':
        save()
    elif p == '2':
        load()
    elif p == '3':
        print('Goodbye!')
        break;

    else:
        print('Error!')
 
Joined
Jan 26, 2023
Messages
9
Reaction score
0
#Okay. I see. It has been done. But what if 1 save, 2 show, 3 check as long as saved data is in the file. It just if as it was a login by #registration.

Python:
from pathlib import Path

file=Path('file.txt')

def save_data():
    with open(file,'w') as f:
        f.write(input('data:'))


def load_data():
    if file.is_file():
        with open(file,'r') as f:
            print(f.read())

    else:
        print('file does not exist')

# I know here is fucked up story_ I know how it would be look, but can not get right on the money.
def check_d():
    check=input('check:')
    if file.is_file==file:
        print('success')
       

        return check


while True:
    p=print('1 save, 2 show, 3 check')
    p=input()
    if p=='1':
        save_data()
    elif p=='2':
        load_data()
    elif p=='3':
        check_d()
 
Joined
Dec 10, 2022
Messages
73
Reaction score
22
This append to file instead of writing over the file

Python:
# Import Path from pathlib. This will give a file path and allow us to test
# if the file exist
from pathlib import Path

# Create the file path. This will be the current project directory
file = Path('file.txt')

# Define the function for saving input data
# Opens the file and ask for input then writes
# w will overwrite the current file. Use a to append data
def save():
    with open(file, 'a') as f:
        f.write(input('data: ')+"\n")

# Define a function for loading and reading the file
# We use file.is_file() for testing if the file exist.
# If the file does not exist give an error message
def load():
    if file.is_file():
        with open(file, 'r') as f:
            print(f.read())
    else:
        print('File does not exist')

# Define a check file function
# Open file and read
# Test if user(arg) is in the file. If found return True Else return False
def check(arg):
    if file.is_file():
        with open(file, 'r') as f:
            if arg in f.read():
                return True
            return False
        

# Start the while loop
while True:

    # Print out the menu

    print('1 Save, 2 Show, 3 Check , 4 Exit')

    # Prompt
    p = input('>> ')

    # If 1 is entered, call the save function
    # If 2 is entered, call the load function
    # Get a username and test against the list
    # If 4 is entered, exit the program
    # Else print an error, because no proper input was entered
    if p == '1':
        save()
    elif p == '2':
        load()
    elif p == '3':
        user = input("Enter username\n>> ")
        if check(user):
            print(f'Found {user} in file')
        else:
            print(f'Sorry, did not find {user} in file')
    elif p == '4':
        print('Goodbye!')
        break;

    else:
        print('Error!')
 
Joined
Jan 26, 2023
Messages
9
Reaction score
0
#I see. I realize partly how the mechanism works. At the moment I try to check data by login in, I saved username, I saved password, by cheking I call them from the file_ if arg in f.read(): if passw in f.read(): , but something wrong, I guess it because we need to appoint where in the file is precisely password and login. when I write if arg in f.read() or passw in f.read(): it works, but it doesnt right so. If I write if arg in f.read() and passw in f.read(): it does not work if as username or password were not in the file, although they are there.
#Module
Python:
from pathlib import Path

TextFile1=Path('TextFile1.txt')

def save_data():
    with open(TextFile1,'w') as f:
        f.write(input('user:')+'\n')
        f.write(input('password:')+'\n')


def load_data():
    if TextFile1.is_file():
        with open(TextFile1,'r') as f:
            print(f.read())

    else:
        print('file does not exist')


def check_d(arg,passw):
    if TextFile1.is_file():
        with open(TextFile1,'r') as f:
            if arg in f.read():
                if passw in f.read():
                    return True
                return False

Code:
#Main sheet
while True:
    p=print('1 save, 2 show, 3 check')
    p=input()
    if p=='1':
        save_data()
    elif p=='2':
        load_data()
    elif p=='3':
        user=input('user1:')
        password=input('password1:')
        if check_d(user,password):
            print(f'you logged in')
        else:
            print(f'sorry, has not been found {user}')
 
Joined
Jan 26, 2023
Messages
9
Reaction score
0
If you are going to do a login system would be better to use a database
hi there! what's up ? time fleeting, but the big time is not going to come true. Feel like a cat on a tin roof. Out here is hard nut to crack for me and easy breeze for you. Provided you do not mind. The heart of the matter, I write a dictionary there is an option to transfer words from English to Russian and the opposite. The business is there ought to be the notification as long as I write word which is no out there in the dictionary" there is no such word in the dictionary"

out here is a part of the code, I know how it has to look like kind of
for i in e:
if i not in list:
print('')

smth do wrong after all

Python:
def word_transfer(e:list,l:list): 
    n=input('Which language_? English>:1 Russian>:2')
    if int(n)==1: 
        e=list(map(str,e)) 
        pos=0 
        english=input('English:')
        ind=e.index(english,pos) 
        english=print(l[ind]) 
        pos=ind+1
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,516
Members
44,991
Latest member
Josephnag

Latest Threads

Top