You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取txt文件生成列表后删除元素致终端闪退问题求助

问题描述

我正在开发一个简易任务管理器程序,任务会被添加到列表并保存至task_list.txt文件,以便下次启动程序时仍可对任务进行增删管理。但测试时发现,尝试从列表中删除元素时,终端会突然闪退。

程序通过菜单选项关闭时会保存txt文件;首次运行时会检测该txt文件是否存在,若不存在则直接运行,若存在则读取文件内容并添加到任务列表中。

我在正式开始学习编程前已自学几周,目前仅求助这个闪退问题,以下是完整程序代码:

# TASK MANAGER v0.2 ENGLISH VERSION

import os

margin = " " * 5   # Just a margin in order to clear the terminal on the print() functions. It's just esthetic.


## TASKS LIST. This is the list in which the user adds or remove elements
tasks = []   


## METHODS

def add_task():   # Adds an element to the var: tasks
    return tasks.append(input('NEW TASK: '))

def remove_task():   # Removes an element from the var: tasks
    return tasks.remove(input('REMOVE TASK: '))

def credits():   # Shows the credits
    os.system('cls')
    print(margin + 'TaskManager version 0.2, created by Vicente Pascual Llinares in 05/2023.')
    print(margin + 'In this version, tasks are showed in a list above of the terminal.')
    print(margin + 'You can add and remove any number of elements to the task list.')
    print(margin + 'What is new compared to v0.1 is that tasks are now saved everytime you close de program from the menu.')
    print('')
    input(margin + 'Press ENTER to go back to menu.')

def bugs():   # Shows the bugs
    os.system('cls')
    print(margin + 'BUGS:')
    print('')
    print(margin + 'BUGS:')
    print(margin + '* If an integer isn\'t wrote on the menu, the program closes suddenly.')
    print(margin + '* The program closes by pressing ENTER when it isn\'t expecting that key to be pressed.')
    print(margin + '* When an element is wrote to be removed -in 2) Remove task- from list, the program closes suddenly')
    print()
    input(margin + 'Press ENTER to go back to menu.')

def program():    # Runs the program itself
    start = True
    while start == True:
        print(margin + '####################')
        print(margin + '### TASK MANAGER ###')
        print(margin + '####### v0.2 #######')
        print('')
        print(margin + 'Tasks: ')
        print('')
        for i in tasks:   # Prints the tasks list elements on the terminal
            print(i)
        print()
        print(margin + '--------------------')
        print()

        # This is just a menu
        menu = int(input(margin + '1) Add task\n%s2) Remove task\n\n%s3) CREDITS\n%s4) BUGS\n\n%s5) CLOSE\n\n'%(margin, margin, margin, margin)))

        if menu == 1:
            add_task()
        elif menu == 2:
            remove_task()
        elif menu == 3:
            credits()
        elif menu == 4:
            bugs()
        elif menu == 5:   # Before the program closes, writes an .txt file in order to save the tasks list for a future running of the program.
            open('task_list.txt', 'w')
            for i in tasks:
                with open('task_list.txt', 'a') as f:
                    f.write(i + '\n')
            start = False
        else:
            print(margin + 'Selcet one of the options writing one of the numbers avaibles.')
            input(margin + 'Press ENTER to go back to menu.')

        os.system('cls')   # This manteins the terminal cleaned.
            

## OPENING. 

try:   # Here, Python discovers if already exist a .txt where takes the elements for the list 'tasks'
    file = open('task_list.txt', 'r')
    text = file.read()
    tasks = text.split(',')
    program()
     

except FileNotFoundError:   # If that .txt file doesn't exist, it just run the program itself.
    program()
问题根源

闪退的核心原因有两个:

  • 读写分隔符不匹配:保存任务时用换行符\n分隔条目,但读取文件时错误地用逗号,分割,导致加载的任务列表包含空字符串或格式错乱的内容,删除时找不到对应元素触发ValueError,直接终止程序。
  • 未捕获删除异常:list.remove()方法在目标元素不存在时会抛出ValueError,程序没有处理该异常,一旦触发就会直接崩溃闪退。
修复方案
  • 修正文件读写逻辑:读取文件时用换行符\n分割,同时过滤空行,保证任务列表格式正确。
  • 为删除操作添加异常捕获:当用户输入的任务不存在时,给出提示而非崩溃。
  • 优化文件写入:关闭程序时一次性打开文件完成写入,减少IO操作。
  • 额外优化菜单输入:处理非数字输入的异常,避免其他场景下的闪退。
修复后的完整代码
# TASK MANAGER v0.2 ENGLISH VERSION

import os

margin = " " * 5   # Just a margin in order to clear the terminal on the print() functions. It's just esthetic.


## TASKS LIST. This is the list in which the user adds or remove elements
tasks = []   


## METHODS

def add_task():   # Adds an element to the var: tasks
    tasks.append(input('NEW TASK: '))

def remove_task():   # Removes an element from the var: tasks
    task_to_remove = input('REMOVE TASK: ')
    try:
        tasks.remove(task_to_remove)
        print(margin + f"Task '{task_to_remove}' removed successfully!")
        input(margin + 'Press ENTER to go back to menu.')
    except ValueError:
        print(margin + f"Task '{task_to_remove}' not found in the list.")
        input(margin + 'Press ENTER to go back to menu.')

def credits():   # Shows the credits
    os.system('cls')
    print(margin + 'TaskManager version 0.2, created by Vicente Pascual Llinares in 05/2023.')
    print(margin + 'In this version, tasks are showed in a list above of the terminal.')
    print(margin + 'You can add and remove any number of elements to the task list.')
    print(margin + 'What is new compared to v0.1 is that tasks are now saved everytime you close de program from the menu.')
    print('')
    input(margin + 'Press ENTER to go back to menu.')

def bugs():   # Shows the bugs
    os.system('cls')
    print(margin + 'BUGS:')
    print('')
    print(margin + '* If an integer isn\'t wrote on the menu, the program closes suddenly.')
    print(margin + '* The program closes by pressing ENTER when it isn\'t expecting that key to be pressed.')
    print(margin + '* When an element is wrote to be removed -in 2) Remove task- from list, the program closes suddenly')
    print()
    input(margin + 'Press ENTER to go back to menu.')

def program():    # Runs the program itself
    start = True
    while start == True:
        print(margin + '####################')
        print(margin + '### TASK MANAGER ###')
        print(margin + '####### v0.2 #######')
        print('')
        print(margin + 'Tasks: ')
        print('')
        for idx, task in enumerate(tasks, 1):
            print(margin + f"{idx}) {task}")
        print()
        print(margin + '--------------------')
        print()

        # Handle menu input errors
        try:
            menu = int(input(margin + '1) Add task\n%s2) Remove task\n\n%s3) CREDITS\n%s4) BUGS\n\n%s5) CLOSE\n\n'%(margin, margin, margin, margin)))
        except ValueError:
            print(margin + "Please enter a valid number from 1 to 5.")
            input(margin + 'Press ENTER to go back to menu.')
            os.system('cls')
            continue

        if menu == 1:
            add_task()
        elif menu == 2:
            remove_task()
        elif menu == 3:
            credits()
        elif menu == 4:
            bugs()
        elif menu == 5:   # Before the program closes, writes an .txt file in order to save the tasks list for a future running of the program.
            with open('task_list.txt', 'w') as f:
                for task in tasks:
                    f.write(task + '\n')
            start = False
        else:
            print(margin + 'Select one of the options by writing one of the available numbers.')
            input(margin + 'Press ENTER to go back to menu.')

        os.system('cls')   # This maintains the terminal cleaned.
            

## OPENING. 

try:   # Here, Python discovers if already exist a .txt where takes the elements for the list 'tasks'
    with open('task_list.txt', 'r') as file:
        text = file.read()
        # Split by newlines and filter out empty strings (like trailing newlines)
        tasks = [line.strip() for line in text.split('\n') if line.strip()]
    program()
except FileNotFoundError:   # If that .txt file doesn't exist, it just run the program itself.
    program()

内容的提问来源于stack exchange,提问作者K'Thun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 17:27:56