如何将数组写入.txt文件并通过.txt文件填充相同的数组?

3

我正在开发一个ToDo应用程序,需要将一系列句子和单词保存到.txt文件中。我已经做了一些研究,但没有找到任何能够很好地解释它的教程,以便我能够理解它。正如我所说,我正在使用Python 3。以下是代码:

# Command line TO-DO list
userInput = None
userInput2 = None
userInput3 = None
todo = []
programIsRunning = True

print("Welcome to the TODO list made by Alex Chadwick. Have in mind 
that closing the program will result in your TODO"
  " list to DISAPPEAR. We are working on correcting that.")
print("Available commands: add (will add item to your list); remove 
(will remove item from your list); viewTODO (will"
      " show you your TODO list); close (will close the app")

with open('TODOList.txt', 'r+') as f:
    while programIsRunning == True:
        print("Type in your command: ")
        userInput = input("")

        if userInput == "add":
            print("Enter your item")
            userInput2 = input("")
            todo.append(userInput2)
            continue

        elif userInput == "viewTODO":
            print(todo)
            continue

        elif userInput == "remove":
            print(todo)
            userInput3 = input("")
            userInput3 = int(userInput3)
            userInput3 -= 1
            del todo[userInput3]
            continue

        elif userInput == "close":
            print("Closing TODO list")
            programIsRunning = False
            continue

        else:
            print("That is not a valid command")

programIsRunning == False 是一种比较,而不是赋值。你可能想要将 False 赋值给你的变量,所以请修正为 programIsRunning = False。你最好在开始时将数据读入列表结构中,然后操作该列表以添加/删除待办事项,最后在关闭时将列表保存到文件中。 - Patrick Artner
这篇帖子讨论了如何保存一个字典。保存列表的方法也是一样的。 - taras
2个回答

2
这似乎需要使用pickle!Pickle是Python内置的用于保存对象和数据的模块。要使用它,您需要将import pickle放在程序顶部。要保存到文件,请执行以下操作:
file_Name = "testfile.save" #can be whatever you want
# open the file for writing
fileObject = open(file_Name,'wb') 

# this writes the object to the file
pickle.dump(THING_TO_SAVE,fileObject)   

# here we close the fileObject
fileObject.close()

从文件中加载:
# we open the file for reading
fileObject = open(file_Name,'r')  
# load the object from the file
LOADED_THING= pickle.load(fileObject)  
fileObject.close()

这个答案中的代码来自这里

希望对你有帮助!


在 {testfile.save} 中,我需要包含文件扩展名吗? - Alex Chadwick
@AlexChadwick,您可以有带扩展名或不带扩展名的文件,只需确保使用完全相同的名称(包括扩展名)加载它们即可。扩展名可以是任何内容,而不仅仅是“.save”。 - Luke B
我需要将THING_TO_SAVE更改为数组的名称吗? - Alex Chadwick

0
您可以使用简单的文本文件存储您的 TODO 项并从中检索:
import sys
fn = "todo.txt"

def fileExists():
    """https://dev59.com/SnVD5IYBdhLWcg3wHnwX
    answer: https://dev59.com/SnVD5IYBdhLWcg3wHnwX#82852
    """
    import os

    return os.path.isfile(fn) 

def saveFile(todos):
    """Saves your file to disk. One line per todo"""
    with open(fn,"w") as f: # will overwrite existent file
        for t in todos:
            f.write(t)
            f.write("\n")

def loadFile():
    """Loads file from disk. yields each line."""
    if not fileExists():
        raise StopIteration
    with open(fn,"r") as f:
        for t in f.readlines():
            yield t.strip()

def printTodos(todos):
    """Prints todos with numbers before them (1-based)"""
    for i,t in enumerate(todos):
        print(i + 1, t)

def addTodo(todos):
    """Adds a todo to your list"""
    todos.append(input("New todo:"))
    return todos

def deleteTodos(todos):
    """Prints the todos, allows removal by todo-number (as printed)."""
    printTodos(todos)
    i = input("Which number to delete?")
    if i.isdigit() and 0 < int(i) <= len(todos): #  1 based
        r = todos.pop(int(i) - 1)
        print("Deleted: ", r)
    else:
        print("Invalid input")
    return todos

def quit():
    i = input("Quitting without saving [Yes] ?").lower()
    if i == "yes":
        exit(0) # this exits the while True: from menu()

def menu():
    """Main loop for program. Prints menu and calls subroutines based on user input."""

    # sets up all available commands and the functions they call, used
    # for printing commands and deciding what to do
    commands = {"quit": quit, "save" : saveFile, "load" : loadFile, 
                "print" : printTodos, 
                "add": addTodo, "delete" : deleteTodos}
    # holds the loaded/added todos
    todos = []
    inp = ""
    while True:
        print("Commands:", ', '.join(commands)) 
        inp = input().lower().strip()
        if inp not in commands:
            print("Invalid command.")
            continue
        # some commands need params or return smth, they are handled below
        if inp == "load":
            try:
                todos = [x for x in commands[inp]() if x] # create list, no ""
            except StopIteration:
                # file does not exist...
                todos = []
        elif inp in [ "save","print"]:
            if todos:
                commands[inp](todos) # call function and pass todos to it
            else:
                print("No todos to",inp) # print noting to do message

        elif inp in ["add", "delete"]:
            todos = commands[inp](todos) # functions with return values get 
                                         # todos passed and result overwrites 
                                         # it 
        else: # quit and print are handled here
            commands[inp]()

def main():
    menu()

if __name__ == "__main__":
    sys.exit(int(main() or 0))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接