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

时间:2018-07-28 19:04:50

标签: 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 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")

2 个答案:

答案 0 :(得分: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()

此答案中的代码取自here.

希望对您有帮助!

答案 1 :(得分:0)

您使用一个简单的文本文件来存储您的TODO-项目并从中检索它们:

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