Python 试图从文本文件中获取数据以插入数据库

Python 试图从文本文件中获取数据以插入数据库,python,django,Python,Django,我被困在从文本文件读取数据,我想插入到数据库。 这是我的models.py文件..文本文件保存在静态文件夹中。 settings.py: STATIC_URL = '/static/' STATIC_ROOT=os.path.join(BASE_DIR,'static_cdn') STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static') ] URL.py: if settings.DEBUG: urlpatterns += stati

我被困在从文本文件读取数据,我想插入到数据库。 这是我的models.py文件..文本文件保存在静态文件夹中。 settings.py:

STATIC_URL = '/static/'
STATIC_ROOT=os.path.join(BASE_DIR,'static_cdn')
STATICFILES_DIRS=[
    os.path.join(BASE_DIR,'static')
]
URL.py:

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
models.py:
from django.db import models
import os
from django.conf import settings

# Create your models here.

class Book(models.Model):
    title = models.CharField(max_length=100)
    author=models.CharField(max_length=20,blank=True)
    @classmethod
    def create(cls, title,author):
        obj = cls(title=title,author=author)

        # do something with the book
        return obj

file=open(os.path.join(settings.BASE_DIR,'/static/product.txt','r'))
line=file.readline()
for lines in line:
    split_line=lines.split("|")
    a=split_line[0]
    b=split_line[1]
    obj=Book.create(a,b)
    obj.save()
请帮助我。

您在
'/static/product.txt'
之后缺少一个
,因此总体地址为:

<BASE_DIR>/static/product.txt/r

如果您的文件位于
/static/product.txt

中,那么它应该可以工作。您的实际问题是什么?您打算只读取第一行吗?是的,在我尝试读取时抛出了“未找到文件”错误run@NagarjunaBathula尝试打印
os.path.join(settings.BASE\u DIR,'static/product.txt')
的值,并将其与文件位置进行比较。
file = open(os.path.join(settings.BASE_DIR,'static/product.txt'), 'r')