Python 如何将数组写入.txt文件,然后用相同的.txt文件填充数组?

Python 如何将数组写入.txt文件,然后用相同的.txt文件填充数组?,python,arrays,python-3.x,text-files,Python,Arrays,Python 3.x,Text Files,所以我正在做一个ToDo应用程序,我需要将一组句子和单词保存到一个.txt文件中。我做了一些研究,但还没有找到任何教程可以很好地解释它,使我能够理解它。正如我所说,我正在使用Python3。代码如下: # Command line TO-DO list userInput = None userInput2 = None userInput3 = None todo = [] programIsRunning = True print("Welcome to the TODO list mad

所以我正在做一个ToDo应用程序,我需要将一组句子和单词保存到一个.txt文件中。我做了一些研究,但还没有找到任何教程可以很好地解释它,使我能够理解它。正如我所说,我正在使用Python3。代码如下:

# 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")

这听起来像是泡菜的工作

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()
此答案中的代码取自


我希望这有帮助

您可以使用一个简单的文本文件来存储待办事项并从中检索它们:

import sys
fn = "todo.txt"

def fileExists():
    """https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-fi
    answer: https://stackoverflow.com/a/82852/7505395
    """
    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))
导入系统 fn=“todo.txt” def fileExists(): """https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-fi 答复:https://stackoverflow.com/a/82852/7505395 """ 导入操作系统 返回os.path.isfile(fn) def保存文件(todos): “”“将文件保存到磁盘。每todo一行”“” 将open(fn,“w”)作为f:#将覆盖现有文件 对于TODO中的t: f、 写入(t) f、 写入(“\n”) def loadFile(): “”“从磁盘加载文件。产生每行。”“” 如果文件不存在(): 提出停止迭代 以开放式(fn,“r”)作为f: 对于f.readlines()中的t: 屈服t.带() def打印todos(todos): “”“打印前带数字的TODO(基于1)” 对于枚举中的i,t(TODO): 打印(i+1,t) def ADDDTODO(TODO): “”“将待办事项添加到列表中”“” 追加(输入(“新todo:”) 返回待办事项 def删除todos(todos): “”“打印todo,允许按todo编号(打印时)删除。” 打印todos(todos) i=输入(“要删除哪个号码?”)
如果i.isdigit()和0programIsRunning==False是比较,而不是赋值。您可能希望将t
False
赋值给变量,因此将其固定为
programIsRunning=False
。你最好从一开始就把数据读入一个列表结构中。。。2) 操纵列表以添加/删除待办事项。。。3) 关闭时再次将列表保存到文件中。讨论如何保存词典。保存列表也是一样的。我必须在{testfile.save}中包含扩展名吗?@AlexChadwick如果文件有扩展名或没有扩展名,请确保加载的文件具有相同的确切名称,包括扩展名。扩展名可以是任何内容,而不仅仅是
.save
。我是否必须将数组名称的东西\u更改为\u save?