无法填写数据文件

时间:2015-03-31 08:08:54

标签: python django file csv

我在django工作。我需要从数据库中填写文本文件数据。在数据库中搜索数据并更改其工作的过程,如果我使用print进行调试,则变量不为空。它们包含数据库中的数据。

# encoding: utf-8
# !/usr/bin/python

from django.core.management.base import BaseCommand
import os
from core.db import KeyStore, Fingerprints
import csv
class Command(BaseCommand):
    help = u"Переименование файлов кейсторов и обновление данных о них в БД."

    def handle(self, *args, **options):
        success_csv = 'success_log.csv'
        error_csv = 'error_log.csv'
        [OUTPUT IN FILE]
        with open(success_csv, 'w') as f:
            f.write('Id;Alias;Old keystore;New keystore;\n')
        [OUTPUT IN FILE]
        with open(error_csv, 'w') as f:
            f.write('Keystore;\n')

        path = '/home/anton/PycharmProjects/apps-ittop-mobi/src/media/keystores'
        list_of_files = os.listdir(path)
        count_of_files = len(list_of_files)
        os.chdir(path)
        for i in range(0, count_of_files):
            old_keystore = 'keystores/%s' % list_of_files[i].encode('utf-8')
            try:
                keystore = KeyStore.objects.get(keystore=old_keystore)
            except(ValueError, KeyStore.DoesNotExist):
                keystore = None
                [NOT OUTPUT IN FILE]
                with open(error_csv, 'a') as f:
                    f.write('%s\n' % old_keystore)
            else:
                try:
                    fingerprints = Fingerprints.objects.get(keystore_id=keystore.pk)
                except(ValueError, Fingerprints.DoesNotExist):
                    fingerprints = None
                else:
                    new_keystore = '%s__%s__.keystore' % (keystore.alias, keystore.keypass)
                    keystore.keystore = 'keystores/%s' % new_keystore
                    keystore.save()
                    fingerprints.save()
                    [NOT OUTPUT IN FILE]
                    with open(success_csv, 'a') as f:
                        f.write('%s;%s;%s;%s;\n' % (keystore.pk, keystore.alias, old_keystore, keystore.keystore))

                    os.rename(os.path.join(path, list_of_files[i]), os.path.join(path, new_keystore))

即使我更换:

[NOT OUTPUT IN FILE]
with open(error_csv, 'a') as f:
    f.write('%s\n' % old_keystore)

[NOT OUTPUT IN FILE]
with open(error_csv, 'a') as f:
       f.write('TESTtestTEST\n')

在文件中没有写任何内容。虽然这些代码部分有效:

[OUTPUT IN FILE]
with open(success_csv, 'w') as f:
       f.write('Id;Alias;Old keystore;New keystore;\n')
[OUTPUT IN FILE]
       with open(error_csv, 'w') as f:
            f.write('Keystore;\n')

文件没有填充数据的原因是什么?

0 个答案:

没有答案