Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在Django命令中创建和读取临时文件_Python_Django_Temporary Files - Fatal编程技术网

Python 在Django命令中创建和读取临时文件

Python 在Django命令中创建和读取临时文件,python,django,temporary-files,Python,Django,Temporary Files,我需要将流url读取为csv,然后我会这样做: class Command(BaseCommand): help = 'Admin command to import feed' def _download_flow(self, url): req = requests.get(url, stream=True) if req.status_code == 200: tmp = tempfile.NamedTempora

我需要将流url读取为csv,然后我会这样做:

class Command(BaseCommand):
    help = 'Admin command to import feed'

    def _download_flow(self, url):
        req = requests.get(url, stream=True)

        if req.status_code == 200:
            tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".csv")
            for line in req.iter_lines():
                tmp.write(line)
            return tmp
        raise Exception('error:{}'.format(req.status_code))

    def handle(self, *args, **options):
        catalog = self._download_flow(options['url'])
        with open(catalog.name, 'rU') as csvfile:

            reader = csv.DictReader(
                csvfile,
                delimiter=';',
                quotechar='"')

            for row in reader:
                raise Exception(row)

        catalog.close()
基本上,我从一个url创建一个临时csv文件。然后,现在我想解析这个文件来处理行,但我不知道为什么没有引发异常。(我的文件有内容,我已检查)。 你有什么线索可以帮我吗


谢谢

问题来自_download()方法,正确的文件构造方法是:

    def _download_flow(self, url):
        req = requests.get(url, stream=True)

        if req.status_code == 200:
            tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".csv")
            for chunk in req.iter_content():
                tmp.write(chunk)
            return tmp
        raise Exception('error:{}'.format(req.status_code))