Name: Anonymous 2010-03-12 13:24
How does /prog/ like my text editor?
def is_txt(filename):
if filename[-4:] == '.txt': return True
else: return False
def file_exists(filename):
try:
in_file = open(filename, "rt")
in_file.close
return True
except IOError:
return False
def list_files():
import os
for filename in os.listdir(os.getcwd()):
if is_txt(filename): print filename
def choice_handler(choice):
if choice == "##EXIT##": return
elif choice == "##NEWF##": new_file()
elif choice == "##OPEN##":
while True:
filename = raw_input("Enter file name to open\n##LIST## lists all .txt files in directory\n##BACK## returns to previous menu\n")
if filename == "##LIST##": list_files()
elif filename == "##EXIT##": return
elif filename == "##BACK##": main_menu(); return
elif not is_txt(filename): print "Error: Filename MUST end in .txt\nTry again."
else:
if file_exists(filename): file_io(filename); return
else: print "Error: File does not exist.\nTry again."
return
def new_file():
while True:
filename = raw_input("Enter a new file name\n##LIST## lists all .txt files in directory\n##BACK## returns to previous menu\n")
if filename == "##LIST##": list_files()
elif filename == "##EXIT##": return
elif filename == "##BACK##": main_menu(); return
elif not is_txt(filename): print "Error: Filename MUST end in .txt\nTry again."
else:
if file_exists(filename):
overwrite = raw_input("File already exists. Overwrite? (Y/N): ")
if overwrite.lower() == 'y':
out_file = open(filename, "wt")
out_file.close()
file_io(filename)
else: new_file()
else:
out_file = open(filename, "wt")
out_file.close()
file_io(filename)
return
def file_io(filename):
run_io = 1
print "Type ##EXIT## to exit program\n-----------------------------"
in_file = open(filename, "rt")
text = in_file.read()
print text
in_file.close()
while run_io == 1:
in_text = raw_input()
if in_text == '##EXIT##':
try:
out_file.close()
return
except UnboundLocalError:
return
run_io = 0
else:
in_file = open(filename, "rt")
text = in_file.read()
in_file.close()
out_file = open(filename, "wt")
out_file.write(text + "\n" + in_text)
out_file.close()
return
def main_menu():
run = 1
while run == 1:
choice = raw_input("Options:\n##OPEN## to open a file\n##NEWF## to create a new file\n##EXIT## to exit\n")
if choice=="##LIST##": list_files()
elif choice=="##BACK##": print "Error: This is the top menu"
elif choice=="##HELP##": print "Available commands:\n##BACK##\n##EXIT##\n##HELP##\n##LIST##\n##NEWF##\n##OPEN##"
elif choice=="##OPEN##" or choice=="##NEWF##" or choice=="##EXIT##":
choice_handler(choice)
run = 0
else: print "Invalid choice, please try again."
main_menu()