如何在python中保存修改后的列表数据?

时间:2018-03-23 21:02:23

标签: python python-3.x savechanges custom-lists

我正在建立一个简单的小程序来帮助自己学习语言和其他东西。

概念很简单,我将输入单词,定义和翻译等列表。脚本将一次打印一个列表中的这些项目,然后等待我输入y(是我想从列表中删除此单词)或n(我不想从列表中删除此单词并附加列表)

目的是使用它有点像闪存卡。

例如,我列出的用于学习西班牙语的打印输出:

python : pitón

如果我记住该项目,我将输入y从我的列表中删除该项目。如果我需要更多练习,我会输入n来附加列表中的项目。

以下是可正常运行的代码示例。

words = ['bacon','eggs','bread','cheese','sausage','juice','butter',]

def mylist():
    a_word = words[0]
    yes_or_no = input(a_word)

    if yes_or_no == "n":
        words.append(words.pop(0))

    elif yes_or_no == "y":
        del words[0]
x = 1
while (x < 8):
    mylist()
    x = x + 1

示例输出:

>>> bacon y 
>>> eggs n 
>>> bread y 
>>> cheese n 
>>> sausage y  
>>> juice n  
>>> butter y
>>> print(words)
>>> ['eggs', 'cheese', 'juice']

所以我的问题是:如何让python保存修改后的列表,这样当我再次运行程序时它会加载附加列表?

通过上面的示例,如果我下次打开该程序,该列表将只包含:

['eggs', 'cheese', 'juice']

但不是原作:

['bacon','eggs','bread','cheese','sausage','juice','butter']

2 个答案:

答案 0 :(得分:0)

毫无疑问,你需要数据库。这是一个tutorial

首先创建一个名为wordsdb的数据库,在其中创建一个名为words的表。

mysql -u root -p PASSWORD

> CREATE DATABASE wordsdb

> CREATE table words(word VARCHAR(30) NOT NULL)

好的,你现在准备插入了。

项目的示例代码:

#!/usr/bin/python
import MySQLdb

db = MySQLdb.connect(host="localhost",   # hostname
                     user="username",    # username
                     passwd="password",  # password
                     db="wordsdb")        # dbname

# Cursor object for executing all the queries you need
cursor = db.cursor()

# your codes
words = ['bacon','eggs','bread','cheese','sausage','juice','butter',]
while (x < 8):
    yes_or_no = input(a_word)

    if yes_or_no == "n":
      cursor.execute("INSERT INTO words values(%s)", words.pop(0))

    x = x + 1

# print table, which will always keep your data state
for row in cursor.fetchall():
    print row[0]

db.close()

答案 1 :(得分:0)

使用某些功能,您可以尝试在文件中写入和读取结果:

<强>代码

# Helper functions
def read(fname):
    """Return a list of lines read from a file."""
    with open(fname, "r") as f:
        return [line.strip() for line in f]


def write(fname, data):
    """Write data to a file."""
    with open(fname, "w") as f:
        for line in data:
            f.write(line + "\n")


def keep(word, lst):
    """Return a list keept words."""
    response = input("Keep {}? [y/n]".format(word))
    if response.startswith("y"):
        lst.append(word)
    return lst

关键字:列表理解,字符串格式化,上下文管理器

# Main function
filename = "output.txt"
default_words = ["bacon", "eggs", "bread", "cheese", "sausage", "juice", "butter"]


def ask():
    """Return words written to a file."""
    try:
        items = read(filename)
    except FileNotFoundError:
        items = default_words

    results = []
    for word in items:
        keep(word, results)

    write(filename, results)

    return results

<强>演示

>>> ask()
Keep bacon? [y/n]n
Keep eggs? [y/n]y
Keep bread? [y/n]n
Keep cheese? [y/n]y
Keep sausage? [y/n]n
Keep juice? [y/n]y
Keep butter? [y/n]n
['eggs', 'cheese', 'juice']

>>> ask()
Keep eggs? [y/n]y
Keep cheese? [y/n]y
Keep juice? [y/n]n
['eggs', 'cheese']

<强>详情

我们调用试图读取文件的ask()。如果文件不存在,则使用default_words。如果文件确实存在,则读取文件的行并将其附加到items的列表中。

接下来,询问每个单词是否为keep。已确认的单词将附加到results的新列表中。这些结果写入文件,覆盖先前的数据。

再次ask()时,将使用文件中的单词,并为每次调用重复循环。