这个是一个练习,去尝试写一个to do list,用之前已经学过的知识:
# 连接文件
FILE_NAME = 'todo.txt'
# 展示todo列表
def show_todo_list():
todo_file = open(FILE_NAME, 'r')
counter = 1
for line in todo_file:
line = line.strip('\n')
print(' * (' + str(counter) + ') ' + line)
counter += 1
if counter == 1:
print("没有列表!")
todo_file.close()
# 增加内容
def add_to_todo_list(item):
# 追加模式打开文件
todo_file = open(FILE_NAME, 'a')
todo_file.write(item + '\n')
todo_file.close()
# 删除内容
def remove_from_todo_list(number):
# 只读打开文件
todo_file = open(FILE_NAME, 'r')
new_content = ''
counter = 1
for line in todo_file:
if counter != number:
new_content += line
counter += 1
todo_file.close()
# 写入模式打开文件
todo_file = open(FILE_NAME, 'w')
todo_file.write(new_content)
todo_file.close()
def main():
command = '' # 初始化命令
while command != 'exit':
command = input('show, add, remove, or exit? ')
if command == 'show':
show_todo_list()
elif command == 'add':
task = input('What task needs to be added? ')
add_to_todo_list(task)
elif command == 'remove':
number = int(input('What item number should be removed? '))
remove_from_todo_list(number)
print('结束!')
main()
在相同的目录下,还需要一个todo.txt,请自行添加内容,很遗憾,该代码不支持中文。
发表评论