Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.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 3.x 如何在python中动态创建简单的csv?_Python 3.x_Csv_Byte - Fatal编程技术网

Python 3.x 如何在python中动态创建简单的csv?

Python 3.x 如何在python中动态创建简单的csv?,python-3.x,csv,byte,Python 3.x,Csv,Byte,我有一个接受csv文件的端点 现在,我想编写一个测试,用这个文件发出post请求 我正在尝试动态生成此csv文件(而不是手动创建和存储它) 我试过这个: def csv_fixture(rows, type): headers = None if type == "merchant_upload": headers = MerchantCSV.ordered_columns() elif type == "invoice_upload":

我有一个接受csv文件的端点

现在,我想编写一个测试,用这个文件发出post请求

我正在尝试动态生成此csv文件(而不是手动创建和存储它)

我试过这个:

def csv_fixture(rows, type):
    headers = None
    if type == "merchant_upload":
        headers = MerchantCSV.ordered_columns()
    elif type == "invoice_upload":
        headers = InvoiceCSV.ordered_columns()
    assert headers is not None
    rows = [headers] + rows
    with open("file.csv", "w+") as f:
        writer = csv.writer(f)
        writer.writerows(rows)
        yield f

my_file = csv_fixture(merchants, type="merchant_upload")
request = rf.post("/invoice_admin/upload_organisations/",
                      {"onboarding_file": my_file})

我的端点执行以下操作:

    if filename not in request.FILES:
        raise Exception("Upload Failed: No file submitted.")
    file = TextIOWrapper(
        request.FILES[filename].file, encoding=request.encoding)

    headers = peek_first_row(file)
    missing = required_cols - set(headers)
    if missing:
        raise Exception(f"Columns missing in csv: {str(missing)})")

    return csv.DictReader(file)
如果手动上载文件,则我的端点可以工作。但是,如果我尝试使用第一个snipper以编程方式执行此操作,我会得到一个错误:


    def peek_first_row(file):
        rows = csv.reader(file)
>       headers = next(rows)
E       StopIteration

app/invoice_admin/csv_parser.py:11: StopIteration

请有人给我引路好吗?我看了很多教程,但我在这一点上迷路了

这可能会有帮助

Ex:

def csv_fixture(rows, type):
    headers = None
    if type == "merchant_upload":
        headers = MerchantCSV.ordered_columns()
    elif type == "invoice_upload":
        headers = InvoiceCSV.ordered_columns()
    assert headers is not None
    rows = [headers] + rows
    with open("file.csv", "w+") as f:
        writer = csv.writer(f)
        writer.writerows(rows)
    return open("file.csv", "rb")

my_file = csv_fixture(merchants, type="merchant_upload")
request = rf.post("/invoice_admin/upload_organisations/",
                      files={"onboarding_file": my_file})

非常感谢。这成功了!你知道有一种更像python的方式来编写上述代码吗?不过接收者必须手动关闭文件,对吗?我认为结合使用
with()
yield
会更好?而且我不想存储文件,当前代码存储它