如何将csv文件导入Django项目?

时间:2018-12-28 17:42:19

标签: python django pandas csv

我无法将csv文件导入到我的Django项目中。

我有一个已经可以正常工作的代码,该代码基本上需要一个csv文件并输出不同类别的支出(使用熊猫)。我现在正在学习Django,并且正在尝试将该代码包含到我的项目中。但是每次我尝试运行时都会说'No module named StatementOCTRev'

我不确定这是目录内容还是pandasXdjango东西。

我尝试了不同的方法,但是没有一个起作用。这导致了丑陋的代码。所以我很抱歉无论如何,这是我的view.py:

from django.shortcuts import render, get_object_or_404
from .models import Post
from .budget import Categorize, Spending
import numpy as np
import pandas as pd
import csv
import mysite.StatementOCTRev
from import_export import resources
#import
# Create your views here.
def home(request):
    posts = Post.objects
    return render(request, 'mysite/home.html', {'posts':posts})

def post(request,post_id):

    ################################

    coffeelist = ["WING", "COSTA", "CAFFEINE", "PASSO", "LA FELICE", "GULLUOGLU", "CARIBOU", "ARK COFFEE"]
    restlist = ["TALABAT", "SOLO", "MELENZANE", "PIZZA", "HARDEES", "HARDEE'S", "MCDONALDS", "GULF ROYAL", "SARAY", "Carriage"]
    gaslist = ["KNPC", "OULA", "ALFA"]

    read = pd.read_csv('StatementOCTRev.csv', encoding="ISO-8859-1")  # Read CSV

    # create a new dataframe
    df = pd.DataFrame(columns=["Date", "Reference", "Debit", "Credit", "Balance"])

    df['Date'] = read.iloc[:, 0]
    df['Reference'] = read.iloc[:, 1]
    df['Debit'] = read.iloc[:, 2]
    df['Credit'] = read.iloc[:, 3]
    df['Balance'] = read.iloc[:, 4]
    df['Category'] = 'Misc.'

    for name in df.Debit:
        if name < 0:
            df.loc[df.Debit == name, 'Debit'] = name * -1

    df.Reference = [str(x).replace(str(x), str(x).upper()) for x in df.Reference]
    df.Reference = [x.strip().replace('POS', '') for x in df.Reference]
    df.Reference = [x.strip().replace('UTAP', '') for x in df.Reference]
    df.Reference = [x.strip().replace('@', '') for x in df.Reference]
    df.Reference = [x.strip().replace('-', '') for x in df.Reference]
    df.Reference = [x.strip().replace('_', '') for x in df.Reference]


    # ------------------------ Coffee

    Categorize(coffeelist, "Coffee")
    SpentOnCoffee = Spending("Coffee")

    # ------------------------ Restaurant

    Categorize(restlist, "Restaurant")
    SpentOnRest = Spending("Restaurant")

    # ------------------------ Gas

    Categorize(gaslist, "Gas")
    SpentOnGas = Spending("Gas")

    Other = 1296 - SpentOnRest - SpentOnCoffee - SpentOnGas

    coffeecategorized = Categorize(coffeelist, "Coffee")
    coffeespending = Spending("Coffee")


    post = get_object_or_404(Post, pk=post_id)
    return render(request, 'mysite/post.html', {'post':post})

注意:您可以看到,我不是在告诉post函数返回与该文件相关的任何内容,这是因为实际上我无法再进行任何操作了。我当然要。但我只想让代码首先读取csv文件。

此外,models.py与该csv文件没有任何关系(它只有一个Post类,因为app只是我正在练习Django的博客。)

0 个答案:

没有答案