使用Python,Flask读取CSV文件时出错

时间:2016-08-09 08:00:27

标签: python csv parsing flask

我对python和flask非常新。我只是想读一个CSV文件,但它给我一个错误“FileNotFoundError:[Errno 2]没有这样的文件或目录:'Dog-Data.csv'”我每次尝试运行run.py

以下是我的文件订单

DD\
    static\
        (bunch of image files)
    templates\
        (bunch of template files)
    __init__.py
    views.py
    Dog-Data.csv

views.py

from flask import render_template
from app import app
import csv

@app.route('/')
@app.route('/Home')
def home():
    return render_template("Home.html",title='Home')

@app.route('/MakeaMatch')
def makeamatch():
    return render_template("MakeaMatch.html",title='Make a Match!')

@app.route('/Game')
def game():
    return render_template("Game.html",title='Game')

@app.route('/ListofDogs')
def listofdogs():
    return render_template("ListofDogs.html",title='List of Dogs')

@app.route('/About')
def about():
    return render_template("About.html", title='About')

@app.route('/Contact')
def contact():
    return render_template("Contact.html", title='Contact')

@app.route('/MatchResult')
def matchresult():
    class DogBreed:
        def __init__(self, br, per, si, lif, hou, cli):
            self.breed = br
            self.personality = per
            self.size = si
            self.lifestyle = lif
            self.housing = hou
            self.climate = cli
            self.match = 0

    #List that will contain class DogBreed
    ListOfBreeds = []

    data_file = open('Dog-Data.csv')
    csv_file = csv.reader(data_file)

    for row in csv_file:
        #print (row) #will print the csv file
        #print (row[2]) #will print element of that row
        dog_breed = DogBreed(row[0],row[1].lower().split(", "),row[2].lower(),row[3].lower(),row[4].lower(),row[5].lower())
        ListOfBreeds.append(dog_breed)

    data_file.close()

    #MORE CODES HERE. OMITTED BECAUSE I DON'T THINK IT'S RELEVANT

    return render_template("MatchResult.html",title='Match Result',posts=ListOfBreeds)

如果我注释掉涉及CSV的行,网页加载和模板会显示正常。但是,它当然不会显示我想要的结果。

我也尝试将Dog-Data.csv放入静态文件夹并使用

data_file = open('static/Dog-Data.csv')

但这也不起作用。

非常感谢你的帮助。

2 个答案:

答案 0 :(得分:0)

您是否试图提供完整路径而不仅仅是相对路径?

Python有时将工作目录作为" home"路径,可能与您的view.py相同或不同。

答案 1 :(得分:0)

确定这么简单的错误让我花了好几个小时来解决。 我应该从根文件夹传递它,这意味着我应该把

data_file = open('app/Dog-Data.csv')

现在它有效。 T__T