我不想让函数不被调用

时间:2018-09-24 01:01:59

标签: python python-3.x

我想制作一个Python清单程序,该程序可以读取,删除行并将行附加到记事本上,该记事本位于计算机的我的文档文件夹中。但是它涉及许多互相调用的用户定义函数。

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

我知道使用“ pass”不会做任何事情,但是我不希望你们看到在执行特定操作时我不希望被调用的内容。

1 个答案:

答案 0 :(得分:0)

您应该设计函数,以便一开始就不会调用任何您不想要的东西。如果您想向文件中写入内容,则调用的函数应该做到这一点,并且确切地说是

 autocomplete_fields = ['department', 'location',]

# 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() 方法将删除开头和结尾的空格,这样您就不会得到可能引起问题的多余字符。用户可以选择将其保留为空白,以便根据需要对默认文件路径进行硬编码

编辑:

更改了num_lines参数,使其仅采用正参数(并将转换为负)