【问题标题】:populate text file to database将文本文件填充到数据库
【发布时间】:2017-07-07 17:53:51
【问题描述】:

我正在尝试逐行读取包含一堆单词的文本文件。 我尝试使用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

【问题讨论】:

  • 文件有多大?此外,您没有使用close 或隐式with open file() 明确关闭(或者您没有发布)文件,您的内存泄漏。如果文件很大,您可能会创建一个庞大的数组。
  • 补充我之前所说的......你的words.objects.create() 也没有做任何有用的事情,你没有将数据传递给 create 函数。您提供的链接为您提供了 Representative.objects.create(**dict(zip(fields, row))) 的示例
  • 文件大小为633KB,我使用words.objects.create(wordslist=line)with open(file_path)
  • 所以绝对不是内存。您能否提供文本文件的示例,以便我们可以在本地运行并重现问题。
  • 我让它停止无限循环,但是当我调用Words.objects.all() 时返回<QuerySet [<Words: Words object>, ...] 而不是实际的单词text file is in problem set 3

标签: python django sqlite


【解决方案1】:

这是一个使用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)

【讨论】:

  • 抱歉延迟响应,我尝试在实施您的解决方案时解决问题,但是当我运行此代码from play.models import Words def lines_in_file_to_db(file_path): data = [] with open(file_path) as file: for line in file: data.append(line.strip().lower()) for line in data: Words.objects.create(wordslist=line) lines_in_file_to_db('play/words.txt') 时,它只会挂起,直到键盘中断
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-22
  • 2017-04-17
  • 1970-01-01
相关资源
最近更新 更多