python - 将文本文件填充到数据库

标签 python django sqlite

我正在尝试逐行读取包含一堆单词的文本文件。 我尝试使用 this问题的解决方案,但我无法做到。 这就是我设置 models.py 文件的方式:

from django.db import models
class words(models.Model):
    wordslist = models.CharField(null='True', max_length=128)

我尝试在 python manage.py shell 中运行此代码:

from app.models import words
WORDLIST_FILENAME = "app/words.txt"
inFile = open(WORDLIST_FILENAME, 'r')
wordlist = []
for line in inFile: 
    wordlist.append(line.strip().lower()) # wordlist: list of strings
    words.objects.create()

这最终没有完成,我必须键盘中断。我正在使用 Django 1.11

最佳答案

这是一个使用您的 words 模型从文件中提取行并将其存储在数据库中的工作示例,该模型应大写。

我会将其添加到模型中,因为您将来可能会使用更多文件执行此操作。您可能可以获得文件路径列表并运行 for 循环,将文件路径传递到此函数中以完成工作。

def lines_in_file_to_db(file_path):
    """ Handles reading lines from a file and saving to the Database.

    :param file_path: Path to where file is located.
    :type file_path: str
    """
    data = []

    with open(file_path) as file:
        for line in file:
            # do line manipulation in here...
            line = line.replace('\n', '')
            data.append(line)

    for line in data:
        words.objects.create(wordslist=line)

关于python - 将文本文件填充到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44976939/

相关文章:

python - 将索引上的数据框与 Pandas 合并

python - 如何计算每个 bin 中的点数?

Django- 'WhereNode'对象没有属性 'output_field'错误

python - Django : Passing api's json to template for use in a table

python - Flask-SQLAlchemy 属性错误: can't set attribute

android - SQLite 中的重复条目

python - 在不保留旧父类的情况下用另一个类替换父类

Python - Pandas 使用 np.where 创建列以获取多个不同的值

Django 无法找到 post 变量

python - sqlite3.操作错误: near "?": syntax error in python -- using 'IN' operator