Python:写入文件失败且没有错误 - 导致空文件

标签 python django

我正在使用 Django 来处理上传的文件并将其写入项目中的某个位置。

处理文件上传的 View 是:

def add_data(request):
    # If something was posted

    upload_form = DataImportUploadForm(request.POST, request.FILES) if request.method == 'POST' else DataImportUploadForm() 

    if request.method == 'POST':
        if upload_form.is_valid():
            upload_form.handle_uploaded_file()
            return HttpResponseRedirect(request, '/path/' ) 
        else:
            messages.error(request, ugettext(u"Could not import data"))

    return render_to_response('folder/add.html', {'upload_form': upload_form}, context_instance=RequestContext(request))

形式为:

class DataImportUploadForm(forms.Form):
    file = forms.FileField(label=_(u"File"), required=True)

    def __init__(self, *args, **kwargs):
        super(DataImportUploadForm, self).__init__(*args, **kwargs)
        self.max_upload_size = 1024*1024 #1 MB
        self.fileformat = None
        self.filename = None


    def clean_file(self):
        f = self.cleaned_data.get('file')
        if not f:
            raise forms.ValidationError(_(u"No file uploaded"))

        if f._size > self.max_upload_size:
            raise forms.ValidationError(_(u"Uploaded file is too large ( > 1MB )"))

        try:
            reader = csv.reader(f, csv.get_dialect('excel'))
            reader.next()
            self.fileformat = 'excel'
        except:
            reader = None

        if reader is None:
            try:
                dialect = csv.Sniffer().sniff(f.read(1024))
                f.seek(0)
                reader = csv.reader(f, dialect)
                self.fileformat = 'sniff'
            except:
                reader = None

        if reader is None:
            raise forms.ValidationError(_(u"Unknown data format"))

        self.filename = f._name

        return f

    def handle_uploaded_file(self):
        media_root = settings.MEDIA_ROOT
        file_location = media_root + 'CSV/'
        from core.helpers import ensure_dir
        ensure_dir(file_location)
        f = self.cleaned_data.get('file')
        dest = open(file_location + f._name, 'w+')
        logger.debug(dest)
        for chunk in f.chunks():
            logger.debug(chunk)
            dest.write(chunk)
        logger.debug(dest.closed)
        dest.seek(0)
        logger.debug(dest.read())
        dest.close()

当我上传文件时会发生什么(根据日志文件):

DEBUG 2014-01-31 12:04:46,034 POST URL: localhost.dev/path/?csrfmiddlewaretoken=683FesoraFTYLR7HHxfPuu3bb5xuzPYY&task=upload User: [me] Account: [useraccount]
DEBUG 2014-01-31 12:04:46,126 <open file u'/path/to/project/media/CSV/filename.csv', mode 'w+' at 0x54690c0>
DEBUG 2014-01-31 12:04:46,126 <FILE CONTENTS>
DEBUG 2014-01-31 12:04:46,126 False
DEBUG 2014-01-31 12:04:46,126 <FILE CONTENTS>
DEBUG 2014-01-31 12:04:46,817 GET URL: localhost.dev/path/of/next/view/ User: [me] Account: [useraccont]

我看到的是空文件。

起初我以为这可能是文件权限问题,但 CSV 文件夹有 2777 个权限。并且直到媒体文件夹(包括媒体)的所有文件夹都具有正确的权限,允许访问文件夹。毕竟该死的脚本不会无法生成实际的文件。

任何人都可以指出一些原因,为什么该文件可能最终为空?

(project)alan@alan:/path/to/project/media/CSV$ ls -l
total 0
-rw-rw-rw- 1 alan alan 0 jaan  31 12:19 filename.csv

我使用的Django版本是1.4.2,python版本是2.7.5+。 Nginx + uwsgi & virutalenv + virtualenvwrapper 在 ubuntu 13.10 中。

最佳答案

尝试刷新内部 I/O 缓冲区:

    # … your code …
    with open(file_location + f._name, 'w+') as dest:
        logger.debug(dest)
        for chunk in f.chunks():
            logger.debug(chunk)
            dest.write(chunk)
        dest.flush()

等等......在你的日志中你显示:

    dest.seek(0)
    logger.debug(dest.read())

真的有效吗?那么内容就写完了。

所以要么:

  • 由于拼写错误或其他错误,它被写入错误的路径
  • 由于拼写错误或其他错误,您没有打开正确的文件
  • 或者您的文件被代码中其他位置的内容覆盖

关于Python:写入文件失败且没有错误 - 导致空文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21477859/

相关文章:

python - 构建决策树

Python asyncio wait_for 同步

python - 根据另一列中的值替换 DataFrame 列中的值

python - 以编程方式将图像保存到 Django ImageField 2

Django--停用用户帐户而不是删除它

python - 在 Django 项目中使用 Web 套接字的最佳方法是什么?

python - 属性错误 : 'PyxImporter' object has no attribute 'find_spec' with Pandas/BigQuery

python - get_queryset 中的 Django 2.0 url 参数

django - 在 Django 中的表单上使用cleaned_data

python - 拒绝读取Python文件的部分内容