简体   繁体   English

没有这样的文件或目录:Python CSV

[英]No such file or directory: Python CSV

I'm trying to create a csv file into a different directory. 我正在尝试将csv文件创建到其他目录中。 While running the code on development server it works fine, but on production, it raises an error that No such file or directory: 在开发服务器上运行代码时,它可以正常工作,但在生产环境中,会引发错误,提示No such file or directory:

Following is my code:- 以下是我的代码:

def write_operation(filename,data):
    with open("./static/" + filename, "wb") as f:
        writer = csv.writer(f)
        writer.writerows(data)

@csrf_exempt
def download_data(request):

    if request.POST.has_key('download_data'):
        start_date = str(request.POST['start_date']).replace('/','-')
        end_date = str(request.POST['end_date']).replace('/','-')

        start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d %H:%M")
        end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d %H:%M")


        data.insert(0,('Barcode','Weight', 'Length','Breadth','Height'))
        write_operation('data.csv',data)

        return HttpResponse(json.dumps('Success'),content_type = "application/json")
    ctx = {}
    return render(request, 'dummy/download_data.html', ctx)

The error that I receive is :- 我收到的错误是:-

Exception Value: [Errno 2] No such file or directory: 'static/data.csv'

Here is my directory structure:- 这是我的目录结构:-

├── modules
|   ├── dummy
│   │   └── views.py
├── static

You can use full path to prevent these errors. 您可以使用完整路径来防止这些错误。 For example, your project folder /home/project-name/ . 例如,您的项目文件夹/home/project-name/ You can define a constant to your config and set your project home folder as base_dir . 您可以为配置定义常量,并将项目主文件夹设置为base_dir Then change your code the following: 然后,更改以下代码:

def write_operation(filename,data):
    with open(config.base_dir + "static/" + filename, "wb") as f:
        writer = csv.writer(f)
        writer.writerows(data)

Edit: I missed the script related with the django. 编辑:我错过了与Django相关的脚本。 Above solution is a general solution for python. 上面的解决方案是python的通用解决方案。 Django version is almost the same. Django版本几乎相同。

Add your settings.py file the following lines 在以下几行中添加settings.py文件

import os

BASE_DIR = os.path.dirname(os.path.dirname(__file__))

And change your method with following: 并通过以下方法更改您的方法:

from django.conf import settings
...

def write_operation(filename,data):
with open(settings.BASE_DIR + "static/" + filename, "wb") as f:
    writer = csv.writer(f)
    writer.writerows(data)

In fact, both of them is the same on the base. 实际上,两者在基础上都是相同的。

For avoiding such a problem just use BASE_DIR value, that is initialized and assigned in your project settings.py 为了避免此类问题,请使用BASE_DIR值,该值在项目settings.py中已初始化并分配。

As it is said in official documentation: 如官方文档中所述:

Build paths inside the project like this: os.path.join(BASE_DIR, ...) 像这样在项目内部构建路径:os.path.join(BASE_DIR,...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM