【问题标题】:Django importing text file Data Into sqllit3Django将文本文件数据导入sqllit3
【发布时间】:2019-03-01 05:28:56
【问题描述】:

我已将我的数据的文本文件制成表格,并且记录数量过多,我无法将其一一上传到数据库中 有什么方法可以将该数据导入我在模型中创建的表中

【问题讨论】:

  • 嗨 Yousaf,欢迎来到 SO!您能否更具体一点,您是将文件内容导入数据库还是文件中的多对象、换行符结构?
  • 我有一个用 /t 分隔的文本文件,每一行都是一条新记录,我想将该记录导入数据库,以便为该记录设置查询
  • 好的,所以你有不同的选择如何处理它,要么通过请求处理它,所以你需要某种form,或者你通过命令行管理它,所以你需要python script 来处理它。
  • 我如何使用 python 脚本来做到这一点,就像我们在 mysql 中加载数据文件一样
  • 编写一个 python 脚本,将文本文件以 csv 格式打开,带分隔符 '\t' 并将其插入数据库中。

标签: django database sqlite django-models


【解决方案1】:

我创建了一个简单的脚本,可以作为您的开始。该脚本将读取 csv 文件并将其存储到数据库中。您应该能够修改它以满足您的需求,方法是将filename.csv 替换为您的文件位置,并将YourModel 替换为它所代表的实际模型。您还需要将obj.field1 = line[0] 更改为相互匹配的代表列和字段。

import csv

# Open the csv file and reads it into a two dimensional List
with open('filename.csv', 'rb') as f:
    reader = csv.reader(f)
    lines = list(reader)

# Create an empty list of objects of your model
objects = []

# Iterate each record of the csv file
for line in lines:
    # Create an empty instance of your model
    obj = YourModel()
    # Populate the fields of the model based on the record line of your file
    obj.field1 = line[0] # The first column
    obj.field2 = line[1] # The second column
    # Add the model to the list of objects
    objects.append(obj)

# Save all objects simultaniously, instead of saving for each line
YourModel.objects.bulk_create(objects)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    • 2014-12-06
    • 2019-09-01
    • 2014-12-27
    • 1970-01-01
    相关资源
    最近更新 更多