我无法使这段代码的底部起作用。我希望用户能够键入“ back”并返回主菜单。 有没有人可以提供帮助,并且可以解释为什么它无法像我在这里所做的那样起作用?
我已经尝试过更多版本的同一件事,也尝试过使用“ if rf.read()==“ back”“,但我只是无法弄清楚它而已,这使我很烦恼,因此用户可以返回。现在的样子,如果他们不知道文件名或想回去检查它们是否会卡住 导入os,sys
def loop():
while True:
choice = menuchoice()
choiceexec(choice)
def menuchoice():
showmenu()
while True:
validchoices = [1, 2, 3, 4, 5, 6, 7]
try:
choice = int(input("What would you like to do? "))
if choice not in validchoices:
print(repr(choice) + "Invalid menu choice")
if choice in validchoices:
return choice
except ValueError:
print("Invalid choice. Try again!")
def showmenu():
print("1 - Show current directory path")
print("2 - Show file names in current directory")
print("3 - Show all directories and files in current path")
print("4 - Enter new directory path")
print("5 - Read a .txt file in current directory")
print("6 - Write in a .txt file in current directory")
return
def choiceexec(x):
if x == 1:
showdirectory()
if x == 2:
filesindir()
if x == 3:
allinfo()
if x == 4:
newpath()
if x == 5:
opentxtfile()
if x == 6:
writetxtfile()
if x == 7:
exit()
#def:
def showdirectory():
print(os.getcwd())
print("\n")
def filesindir():
print(os.listdir())
print("\n")
def allinfo():
for dirpath, dirnames, filenames in os.walk(".", topdown=False):
print("Current path: ", dirpath)
print("Directories: ", dirnames)
print("Files: ", filenames)
print("\n")
def newpath():
pathinput = input("Enter new directory path: ")
os.chdir(pathinput)
print("Current path is now:", pathinput)
print("\n")
return
def opentxtfile():
openfile = input("Enter the .txt file name: ")
with open(openfile, 'r') as f:
f_content = f.read()
print(f_content)
print("\n")
f.close()
def writetxtfile():
try:
openfile = input("Enter the .txt file name, or type 'back' to go back to menu: ")
with open(openfile, 'r') as rf:
f_content = rf.read()
print("Current file text:",f_content)
print("\n")
writeinput = input("What would you like to write?")
with open(openfile, 'a') as wf:
wf.write(" " + writeinput)
wf.close()
except:
print("Invalid input")
writetxtfile()
else: #### not working
if openfile == "back":
return
def exit():
sys.exit()
loop()
答案 0 :(得分:1)
您可能希望将writetxtfile()
更改为:
def writetxtfile():
try:
openfile = input("Enter the .txt file name, or type 'back' to go back to menu: ")
if openfile == "back":
return
else:
with open(openfile, 'r') as rf:
f_content = rf.read()
print("Current file text:",f_content)
print("\n")
writeinput = input("What would you like to write?")
with open(openfile, 'a') as wf:
wf.write(" " + writeinput)
wf.close()
except:
print("Invalid input")
writetxtfile()