【问题标题】:django: how to read and manipulate .csv file from View.pydjango:如何从 View.py 读取和操作 .csv 文件
【发布时间】:2021-12-10 08:06:26
【问题描述】:

我正在尝试使用位于 django 应用程序内的 csv 文件。我正在尝试使用 pandas 加载文件,例如:pd.read_csv("...") 没有成功,我一直收到错误。

这是目录树的样子:

├── __pycache__
│   ├── forms.cpython-36.pyc
│   ├── models.cpython-36.pyc
│   ├── views.cpython-36.pyc
│   └── urls.cpython-36.pyc
├── apps.py
├── files
│   ├── t1.csv
│   ├── t2.csv
│   ├── t3.csv
│   ├── t4.csv
│   └── parametre.csv
├── finished_apps.py
├── forms.py
├── migrations
│   ├── 0001_initial.py
│   ├── __init__.py
│   └── __pycache__
│       ├── 0001_initial.cpython-36.pyc
│       ├── 0002_remove_carriers_carriersheet.cpython-36.pyc
│       ├── 0003_auto_20211021_1200.cpython-36.pyc
│       ├── 0004_auto_20211021_1203.cpython-36.pyc
│       └── __init__.cpython-36.pyc
├── models.py
├── views.py
├── templates
│   ├── add_carrier.html
│   ├── base.html
│   ├── delete_carrier.html
│   ├── delete_carrier_confirmation.html
│   ├── _carrierdetails.html
│   ├── _carrierlist.html
│   ├── simulation.html
│   └── update_carrier.html
└── urls.py

我在views.py中尝试了以下内容

df = pd.read_csv("/files/t1.csv") #not working
df = pd.read_csv("./files/t1.csv") #not working
df = pd.read_csv("t1.csv") #not working
df = pd.read_csv("../files/t1.csv") #not working

我也试过这样做:

from files import t1

我得到的错误是这样的:

No such file or directory (/file/t1.csv) #for example
cannot import name 't1'

这也不行。

我现在想知道是否可以通过这种方式导入文件,或者我在这里遗漏了一些明显的东西!

【问题讨论】:

  • 你能提供你得到的错误吗?
  • df = pd.read_csv("carrier/files/t1.csv") 如果carrier 是您的应用名称
  • 不幸的是没有成功

标签: python django pandas csv


【解决方案1】:

__file__ 变量中获取views.py 的路径,并使用它来查找您的CSV 的路径:

import os
import pandas as pd

path = os.path.join(os.path.dirname(__file__), 'files/t1.csv')
df = pd.read_csv(path)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 2010-09-29
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    • 2019-05-27
    • 1970-01-01
    相关资源
    最近更新 更多