Python 3.x 如何在python中动态创建简单的csv?
我有一个接受csv文件的端点 现在,我想编写一个测试,用这个文件发出post请求 我正在尝试动态生成此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":
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
会更好?而且我不想存储文件,当前代码存储它