如何使用 Python 删除列表中的元素,哪些元素是从 .txt 文件中读取的?

How can I remove elements in a list which elements are read from a .txt file using Python?

提问人:K'Thun 提问时间:5/4/2023 更新时间:5/4/2023 访问量:60

问:

我正在做一个简单的任务管理器程序。任务将添加到列表中并保存在 .txt 文件中,以便在下次打开程序时仍可以对其进行管理(从列表中添加/删除)。然而,在测试程序时,我发现当我尝试从列表中删除一个元素时,终端会突然关闭。

每次从程序的菜单选项关闭终端时,都会保存 .txt 文件。此外,程序第一次执行时,它会搜索 .txt 文件是否存在:如果没有,程序就会运行;如果已经存在,Python 会读取 .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()
    

当程序不使用 .txt 文件时,它可以正常工作。但是我希望有一个保存选项,以免丢失我添加过一次的任务,并且能够在列表中添加或删除任何元素(任务)。

Python 数组 列表 文件

评论

1赞 OneCricketeer 5/4/2023
就其本身而言,什么都不做。为什么不在那条线上使用呢?open('task_list.txt', 'w')with
0赞 OneCricketeer 5/4/2023
此外,与其来回读取列表和文件,不如尝试 sqlite 模块
0赞 K'Thun 5/4/2023
@OneCricketeer 那我就学sqlite模块了,非常感谢!事实上,我将在几个月后开始 IA 工程,我想知道一些编程基本技能,所以你的建议肯定会对我有帮助。

答:

0赞 Muhammad Ahmad 5/4/2023 #1

这是因为在 try 块中,您使用它使用“,”作为分隔符,同时当您在 .txt 文件中写入任务时,您在这里使用“\n”作为分隔符。因此,当程序运行时,它不会将文件中的任务保存到 tasks= [ ] 列表中。当您输入要从列表中删除的任务时,它会为您提供“ValueError”并且程序停止。 首先,当您在 .txt 文件中编写任务时,请使用“w”而不是“a”,因为“a”用于追加,它将复制 .txt 文件中的任务。tasks = text.split(',')f.write(i + "\n")

with open("task_list.txt", "w") as f:
                for i in tasks:  #
                    f.write(i + "\n")

然后改用 f.readlines,然后使用列表推导式将任务保存在任务 [ ] 中

try:
    f = open("task_list.txt", "r")
    lines = f.readlines()
    tasks = [line.strip() for line in lines]  # Remove newline characters from each line
    program()

现在,您可以轻松地从列表中删除任务并将它们再次写入 txt 文件,而不是附加它并创建重复项。