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

2024-09-27 00:12:49 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我在做一个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")

Tags: thetoinnoneyourwilltodolist
2条回答

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

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

这听起来像是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()

这个答案中的代码取自here.

我希望这有帮助

相关问题 更多 >

    热门问题