简体   繁体   中英

I Can't stop functions from being called when I don't want them to

I wanted to make a Python listing program that can read, remove and append lines onto a notepad located in my documents folder on my computer. but it involves many user defined functions that call each other.

def main():
    print("To Add, Type A.\nTo Read, Type B")
    c = input(">>>_ ").lower()
    if c == 'a':
        addline()
        pass readout()
    if c == 'b':
        readout()
        pass addline()
main()

def addline():
    with open(r'C:\Users\MI\Documents\PyLists\A\AList.txt', 'a+') as f:
        f_contents = f.read()
        addlyne = input('Add A Line >>>_ ')
        f.write(addlyne + '\n')
addline()

def readout():
    with open(r'C:\Users\MI\Documents\PyLists\B\BList.txt', 'r') as 
        f_contents = f.read()
        print(f_contents)
        f.close()
readout()

I'm aware that using "pass" won't do anything but I wan't you guys to literally see what I don't want being called when a certain action is taken.

You should be designing your functions so that you aren't calling anything you don't want in the first place. If you want to write something to a file, the function called should do that, and precisely that

# The line arg here comes from user input
def add_line(path=None, line):
    # Maybe you'll want a default path unless a user wants to append to a different function
    if not path:
        path = 'C://path/to/file.txt'

    # Open in append mode
    with open(path, 'a') as fh:
        fh.write(line)
        # If you want to see something was written
        print("Wrote %s to file" % line)

# Add arg in case a user wants multiple lines
def read_line(path=None, num_lines=0):

    if not path:
        path = 'C://path/to/file.txt'

    with open(path) as fh:
        lines = fh.readlines()

    # Convert lines to a string here
    if num_lines >= len(lines):
        print('\n'.join(lines)
    else:
        print('\n'.join(lines[:(-1 * abs(num_lines))])


def main():
    input_path = input("What file do you want to edit? (may be left blank)")

    user = input("What do you want to do (add/read)?")

    if user.lower().strip()=="add":
        line = input("Type what you want to add (one line)")
        add_line(path=input_path.strip(), line)

    elif user.lower().strip()=="read":
        read_line(path=input_path.strip())

    else:
        raise ValueError("Invalid input, expected read or write")

if __name__ == "__main__":
    main()

The strip() method will remove leading and trailing whitespace, that way you don't get extra characters that could cause issues. The user has the option to leave it blank so you can hard-code a default file path if you want

Edit:

Changed the num_lines argument so that it takes only positive arguments (and will convert negatives)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM